linux中的set,linuxset
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.testcat a.testecho $?cat b.testecho $?cat b.test | echo "hi"echo $?
cat a.test | echo "hi"
echo $?
執行結果如下:
linux-UMLhEm:/home/test/shell # sh -x tst.sh+ cat a.testcat: a.test: No such file or directory+ echo 11+ cat b.test----this is a test-----+ echo 00+ cat b.test+ echo hihi+ echo 00+ cat a.test+ echo hihicat: a.test: No such file or directory+ echo 00
可以看到在執行 cat a.test | echo "hi" 時,返回的是最右邊命令執行的結果。
下面設定set -o pipeline,樣本如下:
set -o pipefailcat b.test | echo "hi"echo $?cat a.test | echo "hi"echo $?
輸出結果如下:
+ set -o pipefail+ cat b.test+ echo hihi+ echo 141141+ cat a.test+ echo hihicat: a.test: No such file or directory+ echo 11