评估bash“&&”退出代码行为

时间:2016-06-15 14:26:59

标签: bash return return-value

我们最近有一次关于bash的经历,即使我们找到了一个解决方案,它仍然在扭曲我的想法。 bash如何根据返回码评估&&表达式?

执行此脚本,因为myrandomcommand不存在而失败:

#!/bin/bash

set -e

echo "foo"
myrandomcommand
echo "bar"

结果是预期的结果:

~ > 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语句未执行(因为第一个语句失败并且不评估第二个语句),但脚本的行为非常不同:

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

我们发现使用括号(myrandomcommand && ls)之间的表达式可以正常工作(如第一个示例),但我想知道原因。

1 个答案:

答案 0 :(得分:12)

您可以阅读 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.