评估bash"&&"退出代码行为

jau*_*ume 9 bash return return-value

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

执行此脚本,该脚本应该失败,因为myrandomcommand它不存在:

#!/bin/bash

set -e

echo "foo"
myrandomcommand
echo "bar"
Run Code Online (Sandbox Code Playgroud)

结果是预期的一个:

~ > bash foo.sh 
foo
foo.sh: line 6: myrandomcommand: command not found
[exited with 127]
~ > echo $?
127
Run Code Online (Sandbox Code Playgroud)

但是使用&&表达式略微改变代码:

#!/bin/bash

set -e

echo "foo"
myrandomcommand && ls
echo "bar"
Run Code Online (Sandbox Code Playgroud)

ls语句未执行(因为第一个语句失败并且不评估第二个语句),但脚本的行为非常不同:

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

我们发现使用括号之间的表达式(myrandomcommand && ls)它按预期工作(如第一个例子),但我想知道原因.

Jda*_*ian 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.
Run Code Online (Sandbox Code Playgroud)

  • 它在parens中工作的原因是整个子shell失败,它在顶壳中被视为一个命令. (3认同)