linux中的set -e 與set -o pipefail


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

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM