分两部分:
要在任何命令返回错误时立即中止脚本,您需要使用set -e
. 从手册页(BUILTINS 部分;set
内置说明):
-e
Exit immediately if a pipeline (which may consist of a single simple command),
a subshell command enclosed in parentheses, or one of the commands executed as
part of a command list enclosed by braces (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 following the if or elif reserved words, part of any command executed in a
&& or ││ list except the command following the final && or ││, any command in a
pipeline but the last, or if the command's return value is being inverted with
!. A trap on ERR, if set, is executed before the shell exits. This option
applies to the shell environment and each subshell environment separately (see
COMMAND EXECUTION ENVIRONMENT above), and may cause subshells to exit before
executing all the commands in the subshell.
您可以通过三种方式进行设置: 将您的 shebang 行更改为#!/bin/bash -e
; 将脚本称为bash -e scriptname
;或者只是set -e
在脚本顶部附近使用。
问题的第二部分是(解释)如何在退出之前抓住出口并清理。上面引用了答案-您要设置a trap on ERR
.
为了向您展示它们如何协同工作,这里有一个正在运行的简单脚本。请注意,一旦我们有一个非零退出代码,执行就会转移到负责进行清理的信号处理程序:
james@bodacious:tmp$cat test.sh
#!/bin/bash -e
cleanup() {
echo I\'m cleaning up!
}
trap cleanup ERR
echo Hello
false
echo World
james@bodacious:tmp$./test.sh
Hello
I'm cleaning up!
james@bodacious:tmp$