Bash 捕获任何类似 -e 的错误但不退出,执行其他操作

Gre*_*hal 9 bash shell-script error-handling

我想在 shell 脚本 (bash) 中设置一个标志,以便如果有任何返回非零值,则设置一个标志(即设置一个类似 的变量errors="True")。

到目前为止,我想过调用脚本,scriptname.sh 2>Error.log然后执行以下操作:

 if $(wc -l error.log) != 0; then
   errors="True"
Run Code Online (Sandbox Code Playgroud)

必须有更好的方法。请赐教。

jor*_*anm 6

这正是trap ERR它的目的。不幸的是,它与set -e. 例如set -e,任何在条件表达式中返回非零值的命令都会触发陷阱。下面是一些示例代码:

error=0
set_error() {
    (( error++ )) 
}

trap set_error ERR
ls askdjasdaj 2>/dev/null
false
false || true # false returns non-zero but is not counted due to the conditional
echo "$error" # outputs "2"
Run Code Online (Sandbox Code Playgroud)