linux - 为什么 bash 脚本设置了 set -e 并且由 && 连接的两个管道失败

标签 linux bash pipeline

<分区>

假设我们有一个这样的脚本。

#!/bin/bash
set -e
ls notexist && ls notexist
echo still here

不会因为 set -e 退出

但是

#!/bin/bash
set -e
ls notexist || ls notexist
echo still here

会。 为什么?

最佳答案

bash 手册对 set -e 说:

The shell does not exit if the command that fails is [...]
part of any command executed in a && or || list except the
command following the final && or ||

破折号手册说:

If not interactive, exit immediately if any untested command fails.
The exit status of a command is considered to be explicitly tested
if the command is used to control an if, elif, while, or until;
or if the command is the left hand operand of an “&&” or “||” operator.

对于 AND 测试,shell 将在“左手操作数”测试期间提前停止。 因为还有测试,它会认为整个命令都被“测试”,因此不会中止。

对于 OR 测试,shell 必须运行所有(两个)测试,一旦最后一个测试失败,它将断定存在未检查的错误,因此将中止。

我同意这有点违反直觉。

关于linux - 为什么 bash 脚本设置了 set -e 并且由 && 连接的两个管道失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17806394/

相关文章:

c - UNIX 中的 SIZE 命令

python - 有没有办法用 PyGTK AppIndicator 检测鼠标点击

r - 将文件从 Google Cloud Bucket 复制到本地文件夹

linux - qsub 中的别名命令

linux - 如何显示 Bash 字符串中包含的唯一单词?

linux - 显示父目录中文件的内容

gitlab - 如何从 GitLab CI 创建 Jira 任务?

php - Symfony 缓存 :clear Failed to remove directory

powershell - Powershell: “break”似乎结束了整个程序,而不仅仅是循环?

python - TfidfVectorizer NotFittedError