我试图弄清楚如果失败的 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/