As help, you can remember than command when end correctly (without errors) mean true. And his exit codes are zero
so,
- correct = OK = true = exit status 0
- incorrect = BAD = false = exit status > 0
therefore, for example, the correct way deleting all files recursively is
$ pwd
/
$ cd /tnp && rm -rf *
cd: can't change directory #and the rm WILL NOT executed
and not
$ pwd
/
$ cd /tnp ; rm -rf *
cd: can't change directory #but the rm IS executed (in the root directory)
Added:
command1 && command2 && command3
^ ^
| +-- run, only when command2 exited OK (zero)
|
+--run only when command1 exited OK (zero)
So, command3 will not executed if command1 or command2 failed. (when comman1 fails, the command2 will don't execued (fail) so command3 not executed too.
Play with the next
run() {
echo "comand-$2($1)"
return $1
}
ok() {
run 0 $1
}
fail() {
run 1 $1
}
echo "OK && OK && ANY"
ok A && ok B 0 && ok C
echo
echo "OK && FAIL && ANY"
ok A 0 && fail B 1 && ok C
echo
echo "FAIL && ANY && ANY"
fail A && ok B && ok C
echo
echo "OK || ANY || ANY"
ok A || ok B || ok C
echo
echo "FAIL || OK || ANY"
fail A || ok B || ok C
echo
echo "FAIL || FAIL || OK"
fail A || fail B || ok C
echo
echo "FAIL && OK || OK"
fail A && ok B || ok C
echo
the result
OK && OK && ANY
comand-A(0)
comand-B(0)
comand-C(0)
OK && FAIL && ANY
comand-A(0)
comand-B(1)
FAIL && ANY && ANY
comand-A(1)
OK || ANY || ANY
comand-A(0)
FAIL || OK || ANY
comand-A(1)
comand-B(0)
FAIL || FAIL || OK
comand-A(1)
comand-B(1)
comand-C(0)
FAIL && OK || OK
comand-A(1)
comand-C(0)
The last construction is neat, because you can write
command1 && (commands if the command1 is successful) || (commands if not)
&&
"knows" that if it can also be used in a programming context where 0 is false, and everything else is true.a && b
simply means "runa
, and if it succeeds (i.e., exit code of 0), runb
.&&
, despite its appearance, is not a Boolean operator in shell script.