作为帮助,您可以记住命令正确结束时(没有错误)意味着true。他的退出代码为零
所以,
- 正确= OK = true = 退出状态 0
- 不正确 = BAD = false = 退出状态 > 0
因此,例如,递归删除所有文件的正确方法是
$ pwd
/
$ cd /tnp && rm -rf *
cd: can't change directory #and the rm WILL NOT executed
而不是
$ pwd
/
$ cd /tnp ; rm -rf *
cd: can't change directory #but the rm IS executed (in the root directory)
添加:
command1 && command2 && command3
^ ^
| +-- run, only when command2 exited OK (zero)
|
+--run only when command1 exited OK (zero)
因此,如果 command1或command2 失败,则不会执行command3。(当 comman1 失败时,comman2 将不会执行(失败),因此 command3 也不会执行。
玩下一个
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
结果
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)