#!/bin/bash -eu

items="1 2"
for item in $items; do
(
    echo one
    false
    echo two
) ||:
done

I wish false line to break a subshell, but continue processing the outer loop. I.e. the expected output is

one
one

however, I get

one
two
one
two

as if ||: stands exactly after false line, not after the subshell.

Can anyone explain, why does this happen?

有帮助吗?

解决方案

Set -e inside the subshell and remove the ||::

#!/bin/bash -u

items="1 2"
for item in $items; do
(
    set -e
    echo one
    false
    echo two
)
done

Another seemingly working approach is:

#!/bin/bash -eu

items="1 2"
for item in $items; do
(
    echo one
    false
    echo two
) | awk '{print}'
done

I suppose the reason why your approach doesn't work is the following (quoted from man bash):

The shell does not exit if the command that fails is [...] part of any command executed in a && or || list except the command following the final && or ||

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top