2016-06-15 16 views
6

Abbiamo avuto un'esperienza recente con bash che anche se abbiamo trovato una soluzione, continua a turbare la mia mente. In che modo bash valuta l'espressione && in termini di codici di ritorno?Valutazione del comportamento dei codici di uscita di bash "&&"

L'esecuzione di questo script, che dovrebbe fallire perché myrandomcommand non esiste:

#!/bin/bash 

set -e 

echo "foo" 
myrandomcommand 
echo "bar" 

Il risultato è quello atteso:

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

Ma cambiare un po 'il codice utilizzando l'espressione &&:

#!/bin/bash 

set -e 

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

Il ls stat ement non viene eseguito (dal momento che la prima dichiarazione non riesce e non valuta la seconda istruzione), ma lo script si comporta in modo molto diverso:

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

abbiamo scoperto che utilizzando l'espressione tra parentesi (myrandomcommand && ls) funziona come previsto (come il primo esempio), ma mi piacerebbe sapere perché.

+1

[BashFAQ # 105] (http://mywiki.wooledge.org/BashFAQ/105) potrebbe essere una lettura interessante per voi – andlrc

risposta

7

Si può leggere nelle pagine man di bash :

-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

Anche la ragione per cui funziona in Parens, è che l'intera subshell fallisce che conta come un comando nella shell superiore. – 123

Problemi correlati