如果我将 set -e
放入 Bash 脚本中,该脚本将在以后出现错误时退出。我对它如何与函数一起工作感到困惑。考虑以下,它只会打印 one
到标准输出:
set -e # Exit on error
fun(){
echo one
non_existing_command
echo two
}
fun
显然,non_existing_command
是一个错误,因此脚本在第二个 echo
之前退出。通常,当且仅当第一个命令失败时,才可以使用 或 运算符 ||
来运行另一个命令。也就是说,我怀疑以下内容会同时打印出 one
和 three
,但不会打印出 two
:
set -e # Exit on error
fun(){
echo one
non_existing_command
echo two
}
fun || echo three
但是我得到的是一个
和两个
。也就是说,||
运算符会阻止退出(它应该这样做),但它会选择继续执行函数体并忽略右侧的命令。
有什么解释吗?
最佳答案
它似乎记录在 the set
builtin command 中
If a compound command or shell function executes in a context where
-e
is being ignored [such as on the left-hand of a||
], none of the commands executed within the compound command or function body will be affected by the-e
setting, even if-e
is set and a command returns a failure status.
强调和评论是我的。
此外,如果您尝试在函数内set -e
,请不要打扰:下一句:
If a compound command or shell function sets
-e
while executing in a context where-e
is ignored, that setting will not have any effect until the compound command or the command containing the function call completes.
关于Bash 控制流使用 ||在功能上,用 set -e,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45600958/