【问题标题】:Evaluating bash "&&" exit codes behaviour评估 bash "&&" 退出代码行为
【发布时间】:2016-06-15 14:26:58
【问题描述】:

我们最近有一次使用 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) 之间的表达式可以按预期工作(就像第一个示例一样),但我想知道为什么。

【问题讨论】:

标签: bash return return-value


【解决方案1】:

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

【讨论】:

  • 也是它在括号中工作的原因,是整个子shell失败了,这算作顶层shell中的一个命令。
猜你喜欢
  • 2022-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-05
  • 1970-01-01
  • 2013-04-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多