gpt4 book ai didi

bash - 为什么这个 bash 构造有效? (参数替换)

转载 作者:行者123 更新时间:2023-11-29 09:08:51 26 4
gpt4 key购买 nike

代码:${non_existent_variable:+whatever} && echo "它有效"

结果是有效。但为什么? && 评估为空字符串之前的部分。但是尝试运行:&& echo test 给出错误。

我无意中得到了这个,试图为 bash 创建三元运算符替换,并为 set 和 unset 变量提供不同的结果。它以这种方式工作,但我根本不知道为什么它会工作。

PARAM=$(${tested_variable:+false} && echo var_exists || echo var_empty)

最佳答案

根据section 2.9.1 of the POSIX spec :

A "simple command" is a sequence of optional variable assignments and redirections, in any sequence, optionally followed by words and redirections, terminated by a control operator.

2.9.1节的最后一句是相关的:

If there is a command name, execution shall continue as described in Command Search and Execution . If there is no command name, but the command contained a command substitution, the command shall complete with the exit status of the last command substitution performed. Otherwise, the command shall complete with a zero exit status.

因此,如果在所有扩展、重定向等之后,没有找到命令名称,则将其视为成功完成,退出状态为 0。

但是,语法 不允许在 && 运算符之前使用空字符串。以下是语法错误:

&& echo it works

获得完全空的简单命令的唯一方法是在扩展期间使用非空字符串“evaporate”。实现这一点的一种方法是使用生成空字符串的 unquoted 参数扩展,这正是 ${non_existent_variable:+whatever} 所做的。

关于bash - 为什么这个 bash 构造有效? (参数替换),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39086172/

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