<分区>
假设我们有一个这样的脚本。
#!/bin/bash
set -e
ls notexist && ls notexist
echo still here
不会因为 set -e 退出
但是
#!/bin/bash
set -e
ls notexist || ls notexist
echo still here
会。 为什么?
<分区>
假设我们有一个这样的脚本。
#!/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/