为什么设置-e;真放;&安培;假放;&安培;真不退出? [英] Why does set -e; true && false && true not exit?
问题描述
根据此接受的答案使用设置-e
内建应该足够bash脚本在第一个错误退出。然而,下面的脚本:
According to this accepted answer using the set -e
builtin should suffice for a bash script to exit on the first error. Yet, the following script:
#!/usr/bin/env bash
set -e
echo "a"
echo "b"
echo "about to fail" && /bin/false && echo "foo"
echo "c"
echo "d"
打印:
$ ./foo.sh
a
b
about to fail
c
d
删除回声富
确实停止脚本;但是为什么呢?
removing the echo "foo"
does stop the script; but why?
推荐答案
要简化EtanReisner的详细解答,设置-e
仅退出一个'未捕获的错误。你的情况:
To simplify EtanReisner's detailed answer, set -e
only exits on an 'uncaught' error. In your case:
echo "about to fail" && /bin/false && echo "foo"
有故障的code, /斌/假
,后跟&放大器;&安培;
哪些测试它的退出code。由于&放大器;&安培;
测试退出code,假定是程序员知道自己在做什么,并预计该命令可能会失败。因此,这个脚本不会退出。
The failing code, /bin/false
, is followed by &&
which tests its exit code. Since &&
tests the exit code, the assumption is that the programmer knew what he was doing and anticipated that this command might fail. Ergo, the script does not exit.
相比之下,考虑:
echo "about to fail" && /bin/false
该程序不检测或对出口code支线 /斌/假
。所以,当 /斌/假
失败,设置-e
将导致脚本退出。
The program does not test or branch on the exit code of /bin/false
. So, when /bin/false
fails, set -e
will cause the script to exit.
考虑:
set -e
echo "about to fail" && /bin/false ; echo "foo"
如果 /斌/假
失败,此版本将退出。正如情况下&放大器;&安培;
使用,最后陈述回声富
将因此只能被执行如果 /斌/假
是成功的。
This version will exit if /bin/false
fails. As in the case where &&
was used, the final statement echo "foo"
would therefore only be executed if /bin/false
were to succeed.
这篇关于为什么设置-e;真放;&安培;假放;&安培;真不退出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!