2016-06-15 4 views
6

最近私たちが解決策を見つけたとしても、それは私の心をひねり続けるというbashの経験がありました。 bashは戻りコードに関して&&式をどのように評価しますか? myrandomcommandが存在しないため、bash "&&"終了コードの動作を評価する

このスクリプトを実行すると、それは失敗するはずです:

#!/bin/bash 

set -e 

echo "foo" 
myrandomcommand 
echo "bar" 

を結果が1と予想されています

~ > bash foo.sh 
foo 
foo.sh: line 6: myrandomcommand: command not found 
[exited with 127] 
~ > echo $? 
127 

しかし&&式を使用して、わずかにコードを変更:

#!/bin/bash 

set -e 

echo "foo" 
myrandomcommand && ls 
echo "bar" 

ls stat (最初のステートメントが失敗した2番目のステートメントを評価していないので)ementは実行されませんが、スクリプトは非常に異なる動作します。

~ > bash foo.sh 
foo 
foo.sh: line 6: myrandomcommand: command not found 
bar     # ('bar' is printed now) 
~ > echo $? 
0 

は、我々が見つけたようなカッコ期待どおりに動作します(myrandomcommand && ls)間の発現を(使用して最初の例)、なぜ私は知りたいのですが。あなたはbashののmanページで読むことができます

+1

[BashFAQ#105](http://mywiki.wooledge.org/BashFAQ/105)はあなたのための興味深い読み取りかもしれません – andlrc

答えて

7

-e Exit immediately if a simple command (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 in 
    an if statement, part of a && or || list, or if the command's return value is being 
    inverted via !. A trap on ERR, if set, is executed before the shell exits. 
+3

また、それが括弧で動作する理由は、シェル全体が1つのコマンドとして数えられるサブシェル全体が失敗するということです。 – 123

関連する問題