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