Bash 中命令替换变量赋值的退出代码 [英] Exit code of variable assignment to command substitution in Bash
问题描述
我对在执行变量赋值和命令替换时命令将返回什么错误代码感到困惑:
I am confused about what error code the command will return when executing a variable assignment plainly and with command substitution:
a=$(false); echo $?
它输出1
,这让我觉得变量赋值不会在最后一个清除或产生新的错误代码.但是当我尝试这个时:
It outputs 1
, which let me think that variable assignment doesn't sweep or produce new error code upon the last one. But when I tried this:
false; a=""; echo $?
它输出0
,显然这是a=""
返回的并且它覆盖了false
1>.
It outputs 0
, obviously this is what a=""
returns and it override 1
returned by false
.
我想知道为什么会出现这种情况,变量赋值有没有什么特殊性与其他普通命令不同?或者只是因为 a=$(false)
被认为是单个命令并且只有命令替换部分才有意义?
I want to know why this happens, is there any particularity in variable assignment that differs from other normal commands? Or just be cause a=$(false)
is considered to be a single command and only command substitution part make sense?
-- 更新 --
谢谢大家,从答案和评论中我明白了当您使用命令替换分配变量时,退出状态就是命令的状态."(by @Barmar),这个解释非常清晰易懂,但对程序员来说不够准确,我想从 TLDP 或 GNU 手册页等权威机构那里看到这一点的参考,请帮我找到它出来,再次感谢!
Thanks everyone, from the answers and comments I got the point "When you assign a variable using command substitution, the exit status is the status of the command." (by @Barmar), this explanation is excellently clear and easy to understand, but speak doesn't precise enough for programmers, I want to see the reference of this point from authorities such as TLDP or GNU man page, please help me find it out, thanks again!
推荐答案
作为 $(command)
执行命令时允许 替换自身的命令的输出.
Upon executing a command as $(command)
allows the output of the command to replace itself.
当你说:
a=$(false) # false fails; the output of false is stored in the variable a
命令false
产生的输出存储在变量a
中.此外,退出代码与命令生成的代码相同.help false
会告诉:
the output produced by the command false
is stored in the variable a
. Moreover, the exit code is the same as produced by the command. help false
would tell:
false: false
Return an unsuccessful result.
Exit Status:
Always fails.
另一方面,说:
$ false # Exit code: 1
$ a="" # Exit code: 0
$ echo $? # Prints 0
导致对 a
赋值的退出代码被返回,即 0
.
causes the exit code for the assignment to a
to be returned which is 0
.
引用手册:
如果其中一个扩展包含命令替换,则退出命令的状态是最后一个命令的退出状态执行替换.
If one of the expansions contained a command substitution, the exit status of the command is the exit status of the last command substitution performed.
引自 BASHFAQ/002:
如何将命令的返回值和/或输出存储在变量?
...
output=$(command)
status=$?
对output
的赋值对command
的退出状态没有影响,即仍在 $?
中.
The assignment to output
has no effect on command
's exit status, which
is still in $?
.
这篇关于Bash 中命令替换变量赋值的退出代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!