我有一个shell脚本,执行一些命令。我如何使shell脚本退出,如果任何命令退出与非零退出码?


当前回答

[ $? -eq 0 ] || exit $?; # Exit for nonzero return code

其他回答

“set -e”可能是最简单的方法。只要把它放在程序中的任何命令之前。

如果在Bash中只调用exit而不带任何参数,它将返回上一个命令的退出代码。结合OR, Bash应该只在前面的命令失败时调用exit。但是我还没有测试过。

command1 || exit;
command2 || exit;

Bash还将最后一个命令的退出码存储在变量$?

[ $? -eq 0 ] || exit $?; # Exit for nonzero return code

Bash的:

# This will trap any errors or commands with non-zero exit status
# by calling function catch_errors()
trap catch_errors ERR;

#
# ... the rest of the script goes here
#

function catch_errors() {
   # Do whatever on errors
   #
   #
   echo "script aborted, because of errors";
   exit 0;
}

http://cfaj.freeshell.org/shell/cus-faq-2.html#11

How do I get the exit code of cmd1 in cmd1|cmd2 First, note that cmd1 exit code could be non-zero and still don't mean an error. This happens for instance in cmd | head -1 You might observe a 141 (or 269 with ksh93) exit status of cmd1, but it's because cmd was interrupted by a SIGPIPE signal when head -1 terminated after having read one line. To know the exit status of the elements of a pipeline cmd1 | cmd2 | cmd3 a. with Z shell (zsh): The exit codes are provided in the pipestatus special array. cmd1 exit code is in $pipestatus[1], cmd3 exit code in $pipestatus[3], so that $? is always the same as $pipestatus[-1]. b. with Bash: The exit codes are provided in the PIPESTATUS special array. cmd1 exit code is in ${PIPESTATUS[0]}, cmd3 exit code in ${PIPESTATUS[2]}, so that $? is always the same as ${PIPESTATUS: -1}. ... For more details see Z shell.