【问题标题】:bash functions, local variables, and exit codes [duplicate]bash 函数、局部变量和退出代码
【发布时间】:2021-03-03 00:12:18
【问题描述】:

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

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

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

$ foo() { local rv=$(false); echo "code is $?"; }
$ foo
code is 0
$ foo() { rv=$(false); echo "code is $?"; }
$ foo
code is 1

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

【问题讨论】:

  • local rv=$(some_other_function) 还有一个问题——在某些 shell(不包括 bash)中,some_other_function 的输出在传递给 local 之前会被分词;第一个单词将被分配给rv,其余的将被视为单独的标识符以标记为局部变量(那些不是有效标识符的除外)。总是双引号命令替换是最安全的,例如local rv="$(some_other_function)",就像你应该变量引用一样。

标签: bash variables exit-code


【解决方案1】:

谁能给我解释一下?

简单来说,大多数时候$? 的退出状态是最后执行的命令。 last 命令是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 会针对此类错误发出警告。

【讨论】:

猜你喜欢
  • 2012-03-20
  • 2020-11-14
  • 1970-01-01
  • 2022-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-26
  • 1970-01-01
相关资源
最近更新 更多