bash函数、局部变量和退出码



在bash函数中,我试图捕获命令的输出及其退出代码。一般来说,我的表单是

some_function() {
local rv=$(some_other_function)
local code=$?
echo "$rv"
return $code
}

,但我注意到,每当我使用'local',然后$?总是0。它捕获的是赋值的结果,而不是被调用的函数。如果我不使用'local',那么它会按预期工作:

$ foo() { local rv=$(false); echo "code is $?"; }
$ foo
code is 0
$ foo() { rv=$(false); echo "code is $?"; }
$ foo
code is 1
有人能给我解释一下吗?显然有一些基本的东西我就是不明白。

谁能给我解释一下?

简单来说,$?在大多数情况下都是最后一个命令执行的退出状态。去年命令为locallocal的返回状态为零,成功地使rv成为局部变量。愚蠢的例子:

echo $(false) $(true) $(false)
^^^^ - this is the last command executed
# $? here has exit status of **echo**

分隔local的赋值:

local rv code
# Assignment is not a "command", in the sense it preserves exit status.
# The last command executed in assignment is the one inside `$(...)`.
rv=$(some_other_function)
code=$?  # will have the exit status of expression executed inside $(...)

使用http://shellcheck.net检查脚本。Shellcheck警告这些错误。