在Bash中为命令替换分配变量的退出代码 [英] Exit code of variable assignment to command substitution in Bash

查看:81
本文介绍了在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?

-更新-

谢谢大家,我的回答是:当您使用命令替换分配变量时,退出状态就是命令的状态." (由@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 引用:

如何将命令的返回值和/或输出存储在 变量?

How can I store the return value and/or output of a command in a variable?

...

output=$(command)

status=$?

分配给output不会影响command的退出状态,即 仍在$?中.

The assignment to output has no effect on command's exit status, which is still in $?.

这篇关于在Bash中为命令替换分配变量的退出代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆