Why does set -e; true && false && true not exit?
根据这个接受的答案,使用
1 2 3 4 5 6 7 8 9 | #!/usr/bin/env bash set -e echo"a" echo"b" echo"about to fail" && /bin/false && echo"foo" echo"c" echo"d" |
印刷品:
1 2 3 4 5 6 | $ ./foo.sh a b about to fail c d |
删除EDOCX1[1]确实会停止脚本;但是为什么呢?
因为这个答案不够具体。
它应该说(加粗文本是我的补充):
# Any subsequent simple commands which fail will cause the shell script to exit immediately
因为手册页上写着:
1 2 3 4 5 6 7 8 | -e Exit immediately if a simple command (see SHELL GRAMMAR above) exits with a non-zero status. The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test in an if statement, part of a && or ││ list, or if the command’s return value is being inverted via !. A trap on ERR, if set, is executed before the shell exits. |
而
1 2 3 4 5 6 7 8 9 10 | SHELL GRAMMAR Simple Commands A simple command is a sequence of optional variable assignments fol- lowed by blank-separated words and redirections, and terminated by a control operator. The first word specifies the command to be executed, and is passed as argument zero. The remaining words are passed as arguments to the invoked command. The return value of a simple command is its exit status, or 128+n if the command is terminated by signal n. |
为了简化etanreisner的详细答案,
1 | echo"about to fail" && /bin/false && echo"foo" |
失败代码
相比之下,考虑:
1 | echo"about to fail" && /bin/false |
程序不在
考虑:
1 2 | set -e echo"about to fail" && /bin/false ; echo"foo" |
如果
我在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脚本:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #!/bin/bash bash -c"set -e ; true ; echo -n A" bash -c"set -e ; false ; echo -n B" bash -c"set -e ; true && true ; echo -n C" bash -c"set -e ; true && false ; echo -n D" bash -c"set -e ; false && true ; echo -n E" bash -c"set -e ; false && false ; echo -n F" bash -c"set -e ; true || true ; echo -n G" bash -c"set -e ; true || false ; echo -n H" bash -c"set -e ; false || true ; echo -n I" bash -c"set -e ; false || false ; echo -n J" echo"" |
它打印:
1 | ACEFGHI |
关于A:
关于B:
关于C:
这是一个
关于D:
这是一个
关于E:
与c:
关于F:
类似于d:这是一个
关于G:
与c或e的推理相同:
关于H:
这是一个
关于我:
与c、e或g的推理相同:
关于J:
这是一个
您应该能够将这些测试用例应用于您的案例: