Bash 控制流使用 ||在功能上,用 set -e

标签 bash function shell error-handling

如果我将 set -e 放入 Bash 脚本中,该脚本将在以后出现错误时退出。我对它如何与函数一起工作感到困惑。考虑以下,它只会打印 one 到标准输出:

set -e # Exit on error
fun(){
    echo one
    non_existing_command
    echo two
}
fun

显然,non_existing_command 是一个错误,因此脚本在第二个 echo 之前退出。通常,当且仅当第一个命令失败时,才可以使用 运算符 || 来运行另一个命令。也就是说,我怀疑以下内容会同时打印出 onethree,但不会打印出 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/

相关文章:

bash - 查找唯一的文件

linux - 为什么它不起作用?如果bash中的指令

bash - 如何同步(锁定/解锁)从多个脚本访问 bash 中的文件?

R match.fun 看不到导入包的功能

c - 在 Linux 中查找命令的内置和可执行文件的路径

bash - 测试 bash shell 脚本

bash - 在 Bash 中解析日期

bash - 文本处理问题: remove rows where one column does not contain a particular value

php - 引发 SQLSTATE[23000] : Integrity constraint violation: 1062 Duplicate because of unique constraint 的唯一约束

javascript - 如何将长值传递给javascript函数