bash - "set -e"不会导致代码块在有条件的情况下退出

标签 bash

我试图弄清楚如果失败的 block 在条件链中,为什么错误保释行为 -e 不会启动:

#!/bin/bash
set -e
{       echo "First"
        ls blat
        echo "(this should not print)"
}

打印出来:

First
ls: cannot access 'blat': No such file or directory

这是正确的。

鉴于以下内容:

#!/bin/bash
set -e
{       echo "First"
        ls blat
        echo "(this should not print)"
} || echo "Encountered an error"

打印出来:

First
ls: cannot access 'blat': No such file or directory
(this should not print)

我希望打印 Encountered an error 而不是 this should not print

有人可以向我解释造成这种差异的原因吗?

最佳答案

来自文档(强调我的):

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 following the if or elif reserved words, part of any command executed in a && or || list except the command following the final && or ||, any command in a pipeline but the last, or if the command's return value is being inverted with !.

因为 ls 是作为 || 列表的非最终部分执行的 {...} 复合的一部分,所以当 ls 具有非零退出状态时,脚本不会退出。

关于bash - "set -e"不会导致代码块在有条件的情况下退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48211477/

相关文章:

python - 在Python中使用subprocess.Popen执行shell脚本?

c++ - 在 Mac 上构建 opencv 2.4.6 - Mavericks

linux - 添加一个带有字符串的数字变量

Git 跟踪点文件(例如 : . zshrc)

bash - 使用 sed (或类似的)删除重复模式之间的任何内容

perl - 我如何将 Unix/Sed/Perl 的音译 (tr) 应用于特定列?

c - brk() 上的 Bash 脚本段错误

linux - 从脚本运行远程命令

bash - bash shell 脚本中的 -n 运算符代表什么?

linux - 给定目录的输出文件名/行/类型