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

bash: `set -e` does not work when used in if-expression?

看看这个小脚本:

#!/bin/bash

function do_something() {(
    set -e

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

    rsync $( readlink -f "${BASH_SOURCE[0]}" ) /opt/some_folder/ # <== returns 23 -> abort?
    echo "rsync returned $?"                                     # <== sets [=11=] 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_somethingset -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.