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

use*_*007 1 variables bash exit-code

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

some_function() {
local rv=$(some_other_function)
local code=$?
echo "$rv"
return $code
}
Run Code Online (Sandbox Code Playgroud)

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

$ foo() { local rv=$(false); echo "code is $?"; }
$ foo
code is 0
$ foo() { rv=$(false); echo "code is $?"; }
$ foo
code is 1
Run Code Online (Sandbox Code Playgroud)

谁可以给我解释一下这个?显然这里有些基本的东西我只是不明白。

Kam*_*Cuk 5

谁可以给我解释一下这个?

简而言之,大多数时候$?都有最后执行的命令的退出状态。最后一个命令是local. 返回状态local为零——它成功地创建了rv一个局部变量。愚蠢的例子:

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

将作业与 分开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 $(...)
Run Code Online (Sandbox Code Playgroud)

使用http://shellcheck.net检查您的脚本。Shellcheck 对此类错误发出警告。