首页 > 解决方案 > Bash:如何使用局部变量同时捕获错误和回显值?

问题描述

当我试图捕获 shellscript 中的错误时,如果我使用局部变量来捕获回显值,$? 即使函数返回 1,捕获返回值也始终为 0。

这是为什么?

我可以使用全局变量来解决这个问题,但我猜它违反了标准。当我想捕获一些回声值时,是否有更好的方法来处理错误?

谢谢!

例如:

使用局部变量时:

test_error_handle() {
    echo "Some text"
    return 1
}
method() {
    local test=$(test_error_handle) # Use local variable
    echo "$?"
    echo ${test}
}
method

输出:

0
Some text

使用全局变量时:

test_error_handle() {
    echo "Some text"
    return 1
}
method() {
    test=$(test_error_handle) # Use local variable
    echo "$?"
    echo ${test}
}
method

输出:

1
Some text

标签: bashshellerror-handlingechoreturn-value

解决方案


通常退出状态是最后执行的命令的退出状态。

local test=$(test_error_handle)

这里发生的是:

  • 外壳运行命令test_error_handle
  • 然后shell运行命令local
  • local以零退出状态返回

因此,当echo $?您看到local命令的退出状态时。

当你这样做时:

test=$(test_error_handle)

此表达式的退出状态是运行的命令替换的退出状态test_error_handle


推荐阅读