#!/bin/bash -eu
items="1 2"
for item in $items; do
(
echo one
false
echo two
) ||:
done
我希望 false
行中断子 shell,但继续处理外循环。 IE。预期输出是
one
one
但是,我明白了
one
two
one
two
就好像 ||:
恰好位于 false
行之后,而不是子 shell 之后。
谁能解释一下,为什么会发生这种情况?
最佳答案
在子 shell 内设置 -e
并删除 ||:
:
#!/bin/bash -u
items="1 2"
for item in $items; do
(
set -e
echo one
false
echo two
)
done
另一种看似有效的方法是:
#!/bin/bash -eu
items="1 2"
for item in $items; do
(
echo one
false
echo two
) | awk '{print}'
done
我认为您的方法不起作用的原因如下(引自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||
关于bash - make -e 只从子shell退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16586060/