Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
外部脚本函数上的bash命令替换接收到错误的退出状态_Bash_Shell_Command Substitution - Fatal编程技术网

外部脚本函数上的bash命令替换接收到错误的退出状态

外部脚本函数上的bash命令替换接收到错误的退出状态,bash,shell,command-substitution,Bash,Shell,Command Substitution,这个例子是用bash在macel-Capitan上测试的 main_script.sh: 注意:func_a和func_b除了声明局部变量输出的那一行之外是相同的 运行main_脚本时,输出为: A other result (1) -> this is the output <- end B zero result (0) -> this is the output <- end 另一个结果(1)->这是输出这是输出原因是函数b中的$?反映了本地内置的成功,而不是命令

这个例子是用bash在macel-Capitan上测试的

main_script.sh:

注意:func_a和func_b除了声明局部变量
输出
的那一行之外是相同的

运行main_脚本时,输出为:

A other result (1) -> this is the output <- end
B zero result (0) -> this is the output <- end

另一个结果(1)->这是输出这是输出原因是
函数b
中的
$?
反映了
本地
内置的成功,而不是命令替换的成功(
$(…)

如果赋值语法正确,
本地
内置成功
——无论RHS上的任何命令替换是否失败

请注意,这类似于
声明
导出
内置

用一个简单的例子来说明:

declare output="$(false)"; echo $? # -> 0(!) - even though `false` obviously fails.
相比之下,如果不涉及内置项(在简单变量赋值的情况下),则命令替换的失败会反映在
$?
中:

output="$(false)"; echo $? # -> 1(!) - simple assignment; $(...) exit code is reported

这种行为上的反直觉差异可以通过以下事实来解释:
local
/
declare
/
export
是内置的,而不是shell语法的一部分


作为内置命令(内置命令),它们被视为命令,并且命令预期通过其自身的退出代码来表示其成功/失败;如前所述,在所述内置程序的情况下,语法正确的赋值被视为成功—换句话说:如果可以赋值—即使由于RHS上的命令替换失败而导致该值为空字符串—内置程序成功了。

这可能有助于:了解如何调试bash脚本以及set-x的功能。我只是试图让输出尽可能清晰。我知道问题是什么,现在我想知道为什么。似乎无论发生什么情况,声明局部var都返回零。。看起来像是一个狂欢节的臭虫?我想是这样的。声明一个变量会取代赋值的成功,这有点愚蠢。但在shell脚本领域,事情很少是直观的。@arctelix:这绝对是反直观的;我添加了一些背景信息,希望至少能解释为什么会发生这种情况。
declare output="$(false)"; echo $? # -> 0(!) - even though `false` obviously fails.
output="$(false)"; echo $? # -> 1(!) - simple assignment; $(...) exit code is reported