Bash忽略错误并获取返回代码

Viv*_*oel 8 bash

set -e用来中止错误.

但是对于特定的一个函数我想忽略错误并且在出错时我想要返回函数的代码.

例:

do_work || true 
 if [ $? -ne 0 ] 
  then
   echo "Error"
  fi  
Run Code Online (Sandbox Code Playgroud)

但这不是工作返回代码始终是真的由于|| 真正

如何在出错时获取do_work上的返回码?

Jan*_*lho 7

您可以使用子shell快捷方式:

( set +e; do_work )
 if [ $? -ne 0 ]
  then
   echo "Error"
  fi
Run Code Online (Sandbox Code Playgroud)

希望这有助于=)


小智 7

这里给出的几个答案是不正确的,因为它们会导致对一个变量进行测试,如果do_work成功,该变量将是不确定的。

我们还需要介绍成功的案例,因此答案是:

set -eu
do_work && status=0 || status=1
Run Code Online (Sandbox Code Playgroud)

发布者的问题有点模棱两可,因为它在文本中说“错误时我要返回代码”,但随后的代码暗示“我一直想要返回代码”

为了说明,这是有问题的代码:

set -e

do_work() {
    return 0
}

status=123

do_work || status=$?
echo $status
Run Code Online (Sandbox Code Playgroud)

在此代码中,打印的值为123,而不是我们希望的0。


Gor*_*son 6

do_work || {
    status=$?
    echo "Error"
}
Run Code Online (Sandbox Code Playgroud)