本文共 2488 字,大约阅读时间需要 8 分钟。
man set中的解释:
set [--abefhkmnptuvxBCEHPT] [-o option] [arg ...]
set [+abefhkmnptuvxBCEHPT] [+o option] [arg ...]... ... -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 envi- ronment separately (see COMMAND EXECUTION ENVIRONMENT above), and may cause subshells to exit before executing all the commands in the subshell.... ...-o option-name
The option-name can be one of the following:... ...pipefail
If set, the return value of a pipeline is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands in the pipeline exit successfully. This option is disabled by default... ... 个人理解:set -e表示一旦脚本中有命令的返回值为非0,则脚本立即退出,后续命令不再执行;
set -o pipefail表示在管道连接的命令序列中,只要有任何一个命令返回非0值,则整个管道返回非0值,即使最后一个命令返回0.
小实验:
#!/bin/bash# testset.shecho 'disable exit on non-zero return status and pipefail track'set +eset +o pipefaila=$[1/0]|b=2echo 'return status = '$?echo 'disable exit on non-zero return status but enable pipefail track'set +eset -o pipefaila=$[1/0]|b=2echo 'return status = '$?echo 'enable exit on non-zero return status and pipefail track'set -eset -o pipefaila=$[1/0]|b=2echo 'return status = '$?输出结果: [root@desktop2 ~]# ./testset.sh disable exit on non-zero return status and pipefail track ./testset.sh: line 6: 1/0: division by 0 (error token is "0") return status = 0 disable exit on non-zero return status but enable pipefail track ./testset.sh: line 12: 1/0: division by 0 (error token is "0") return status = 1 enable exit on non-zero return status and pipefail track ./testset.sh: line 18: 1/0: division by 0 (error token is "0") [root@desktop2 ~]#
REF:
1. pipefail
http://petereisentraut.blogspot.com/2010/11/pipefail.html
2. linux中的set命令: "set -e" 与 "set -o pipefail"
http://blog.chinaunix.net/uid-15007890-id-3493077.html
转载地址:http://witai.baihongyu.com/