bash: `set -e` 在 if 表达式中使用时不起作用?

标签 bash if-statement subshell

看看这个小脚本:

#!/bin/bash

function do_something() {(
    set -e

    mkdir "/opt/some_folder"                                     # <== returns 1 -> abort?
    echo "mkdir returned $?"                                     # <== sets $0 to 0 again

    rsync $( readlink -f "${BASH_SOURCE[0]}" ) /opt/some_folder/ # <== returns 23 -> abort?
    echo "rsync returned $?"                                     # <== sets $0 to 0 again
)}


# here  every command inside `do_something` will be executed - regardless of errors
echo "run do_something in if-context.."
if ! do_something ; then
  echo "running do_something did not work"
fi

# here `do_something` aborts on first error
echo "run do_something standalone.."
do_something
echo $?

我正在尝试执行建议的操作 here (不要错过引入子 shell 的额外括号)但我没有单独执行函数(在我的例子中是 do_something),而是与 if 表达式一起执行。

现在当我运行 if ! do_something set -e 命令似乎没有效果。

有人能给我解释一下吗?

最佳答案

这是在 Bash Reference Manual 中预期和描述的.

-e

[...] 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 in an if statement, [...].

[...]

If a compound command or shell function executes in a context where -e is being ignored, 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. 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` 在 if 表达式中使用时不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60035954/

相关文章:

c - 为什么 shell 和文件的输出不同

python - 如何测试多个变量与单个值的相等性?

php - if else if 语句不适用于 get

linux - 如何在子shell中设置变量?

linux - 执行单个命令时 Bash 'swallowing' 子 shell 子进程

linux - 从命令行启动 matlab 后,linux 终端中缺少某些内容

bash 突破读取内部陷阱

java - 降低 if-else 语句代码的复杂性

performance - 使用内置函数来增强性能是否会因无故使用子 shell 而被抵消?

linux - bash 空字符串/命令