使用set -e解决程序退出状态的一般解决方案

Pao*_*oni 8 bash exit-code

我现在正在使用Bash进行编程,set -e因为在程序失败时继续执行脚本几乎不是想要的行为.

如果是我使用,||true如果我不需要退出代码.

如果我需要退出代码,我将执行包装如下:

set +e
call_I_need_the_exit_code with few arguments
RV="$?"
set -e
# use "$RV" somewhat
Run Code Online (Sandbox Code Playgroud)

但是,它很冗长,我很少切换set +eset -e引入恼人的错误.

有没有办法创建一个执行命令的函数,并为退出代码设置一个已知变量?

像这样的东西(伪代码):

safe_call( call_I_need_the_exit_code(with, few, arguments) )
# use "$RV" somewhat
Run Code Online (Sandbox Code Playgroud)

其中safe_call基本上是前一段代码.它会使我的代码更容易编写和阅读......

tri*_*eee 5

原因|| true是条件是安全的set -e.这可以轻松扩展到您的场景.

command && rv=0 || rv=$?
Run Code Online (Sandbox Code Playgroud)

顺便说一句,你应该避免使用大写的私有变量.