抑制子shell中的错误?

Phi*_*ide 4 bash

我想在某个时间点后抑制我的子 shell 中的错误。

我写了脚本来演示这种情况:

worked=false
(echo Starting subshell process \
    && echo If this executes process is considered success \
    && false \
    && echo run if possible, but not an error if failed) \
  && worked=true

echo $worked
Run Code Online (Sandbox Code Playgroud)

我想向外壳报告该过程有效。

我还考虑将工作变量放在子shell中:

    && echo This works process worked: \
    && worked=true \
    && false \
    && echo run if possible, but not an error if failed)
Run Code Online (Sandbox Code Playgroud)

但这也不起作用,因为在子外壳内设置变量不会影响主脚本。

roa*_*ima 7

这个怎么样

worked=false
(
    set -e
    echo Starting subshell process
    echo If this executes process is considered success
    false
    echo run if possible, but not an error if failed || true
)
[[ 0 -eq $? ]] && worked=true

echo "$worked"
Run Code Online (Sandbox Code Playgroud)

set -e尽快未受保护的发现错误终止子shell。该|| true构造保护可能会失败的语句,您不希望子shell 终止。

如果您只想知道子shell是否成功,您可以$worked完全省去变量

(
    set -e
    ...
)
if [[ 0 -eq $? ]]
then
    echo "Success"
fi
Run Code Online (Sandbox Code Playgroud)

请注意,如果您想set -e在命令失败后立即中止子 shell 中的执行,则不能使用诸如( set -e; ... ) && worked=trueor 之类的构造if ( set -e; ...); then ... fi。这在手册页中有记录,bash但我第一次错过了:

如果复合命令或 shell 函数-e-e被忽略的上下文中执行时设置,则在复合命令或包含函数调用的命令完成之前,该设置不会产生任何影响。