gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:53:03 25 4
gpt4 key购买 nike

我们最近有一次使用 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 的手册页中阅读:

-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.

关于bash - 评估 bash "&&"退出代码行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37838273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com