linux中的set -e 与set -o pipefail
程序员文章站
2022-06-26 19:51:04
1、set -e "Exit immediately if a simple command exits with a non-zero status." 在“set -e”之后出现的代码,一旦出现返回值非零,整个脚本就会立即退出。 2、set -o pipefail "If set, the re ......
1、set -e
"Exit immediately if a simple command exits with a non-zero status."
在“set -e”之后出现的代码,一旦出现返回值非零,整个脚本就会立即退出。
2、set -o 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 -o pipifail时
#!/bin.bash # there is no a.test,but have b.test cat a.test echo $? cat b.test echo $? cat b.test | echo "hi" echo $?
cat a.test | echo "hi"
echo $?
执行结果如下:
linux-UMLhEm:/home/test/shell # sh -x tst.sh + cat a.test cat: a.test: No such file or directory + echo 1 1 + cat b.test ----this is a test----- + echo 0 0 + cat b.test + echo hi hi + echo 0 0 + cat a.test + echo hi hi cat: a.test: No such file or directory + echo 0 0
可以看到在执行 cat a.test | echo "hi" 时,返回的是最右边命令执行的结果。
下面设置set -o pipeline,示例如下:
set -o pipefail cat b.test | echo "hi" echo $? cat a.test | echo "hi" echo $?
输出结果如下:
+ set -o pipefail + cat b.test + echo hi hi + echo 141 141 + cat a.test + echo hi hi cat: a.test: No such file or directory + echo 1 1