击:变量赋值命令替换的退出code [英] Bash: exit code of variable assignment to command substitution
问题描述
我感到困惑的是什么明明白白,用命令替换执行变量赋值时错误code中的命令将返回:
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
,这让我觉得变量赋值不扫或在最后一个产生新的错误code。但是,当我尝试这样做:
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 =
回报,它会覆盖 1
由归国假
。
It outputs 0
, obviously this is what a=""
returns and it override 1
returned by false
.
我想知道为什么会这样,有没有变量赋值,从其它正常的命令不同的特殊性?或只是事业 A = $(假)
被认为是一个命令,只有命令替换一部分有意义吗?
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?
- 更新 -
谢谢大家,从答案和意见,我拿到了一点当你使用命令替换为变量赋值,退出状态是命令的状态。 (由@Barmar),这个解释是出色清晰和易于理解,但说话并不precise足够的程序员,我希望看到当局如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!
推荐答案
当执行命令为 $(命令)
允许的output更换自己。
当你说:
a=$(false) # false fails; the output of false is stored in the variable a
由命令假生成的输出
存储在变量 A
。此外,出口code是由命令产生的相同。 帮助虚假
会告诉:
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
将导致出口code对分配给 A
要返回这是 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.
我怎么能存储在一个返回值和/或命令的输出
变量?
...
输出= $(命令)
状态= $?
分配到输出
对命令
的退出状态,不影响其
仍然是 $?
。
The assignment to output
has no effect on command
's exit status, which
is still in $?
.
这篇关于击:变量赋值命令替换的退出code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!