gpt4 book ai didi

linux - 变量赋值的退出代码到 Bash 中的命令替换

转载 作者:IT老高 更新时间:2023-10-28 12:36:11 27 4
gpt4 key购买 nike

我对在执行变量赋值和命令替换时该命令将返回什么错误代码感到困惑:

a=$(false); echo $?

它输出 1,这让我认为变量赋值不会扫描或在最后一个错误代码上产生新的错误代码。但是当我尝试这个时:

false; a=""; echo $?

它输出0,显然这是a=""返回的,它覆盖了false返回的1 >.

我想知道为什么会发生这种情况,变量赋值有什么特殊性与其他普通命令不同吗?或者只是因为 a=$(false) 被认为是单个命令并且只有命令替换部分有意义?

-- 更新--

谢谢大家,从答案和评论中我明白了“当您使用命令替换分配变量时,退出状态就是命令的状态。” (@Barmar),这个解释非常清晰易懂,但对程序员来说不够准确,我想从 TLDP 或 GNU 手册页等权威机构中看到这一点的引用,请帮我找到它出来了,再次感谢!

最佳答案

在以 $(command) 执行命令时,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 会告诉你:

false: false
Return an unsuccessful result.

Exit Status:
Always fails.

另一方面,说:

$ false                # Exit code: 1
$ a="" # Exit code: 0
$ echo $? # Prints 0

导致分配给 a 的退出代码返回,即 0


编辑:

引自 manual :

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=$?

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

关于linux - 变量赋值的退出代码到 Bash 中的命令替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20157938/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com