为什么“假&&真实"不能在Bash中使用set -e退出?
问题描述:
为什么第三种情况以退出代码0返回成功?
Why is the third case returning success with exit code 0?
case 1 ~$ bash -c 'set -e; false || true; echo success'; echo $?
success
0
case 2 ~$ bash -c 'set -e; true || false; echo success'; echo $?
success
0
case 3 ~$ bash -c 'set -e; false && true; echo success'; echo $?
success
0
case 4 ~$ bash -c 'set -e; true && false; echo success'; echo $?
1
case 5 ~$ bash -c 'set -e; false || false; echo success'; echo $?
1
case 6 ~$ bash -c 'set -e; false && false; echo success'; echo $?
success
0
答
bash文档对于set -e
说:
如果失败的命令是在
&&
或||
列表中执行的任何命令的一部分,则该外壳程序不会退出,除非最后一个&&
或||
之后的命令[...]. ..]
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||
, [...]
有问题的命令列表是false && true
.失败的命令是false
,它不是列表中的最后一个命令,因此外壳程序不会退出.您看到的0
是echo success
的退出状态.
The command list in question is false && true
. The failing command is false
, which is not the last command in the list, so the shell does not exit. The 0
you're seeing is the exit status of echo success
.