gpt4 book ai didi

linux - 为什么反引号中的嵌套引号在 bash 中有效?

转载 作者:IT王子 更新时间:2023-10-29 00:38:10 24 4
gpt4 key购买 nike

更准确地说,为什么

"`command "$variable"`"

将外部引号视为包含内部引号,而不是将变量扩展到任何引号之外?

我用来测试它的确切命令类似于另一个 stackoverflow 问题中提出的关于使用命令替换时正确引用方法的示例:

fileName="some path with/spaces"
echo "`dirname "$fileName"`"

它正确地回应了“一些路径”,而不是因为无效的参数数量而提示。

我读了 Bash 的手册页,它在“EXPANSION”一章的“Command Substitution”一节中指出,新式 $() 替换保留了括号之间任何字符的含义,但是,关于反引号,它只提到反斜杠以有限的方式工作:

When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by $, `, or \. The first backquote not preceded by a backslash terminates the command substitution.

我的第一个想法是反引号做同样的事情,除了提到的异常(exception),因此“引用”内部双引号,然而,我被告知情况并非如此。将我指向这个方向的第二个观察结果是

a=\$b
b=hello
echo `echo $a`

打印“$b”。如果反引号让美元符号得到解释,那么第一个变量替换应该在子 shell 被调用之前发生,子 shell 扩展字符串“$b”,结果是“hello”。根据手册页的上述摘录,我什至可以通过使用

echo `echo \$a`

结果还是一样。

第三个观察结果让我有些怀疑:

echo `echo \\a`

结果:“\a”

echo \a

结果:一个

这里似乎保留了两个反斜杠,直到子 shell 发挥作用,尽管 手册页指出反引号内的反斜杠在后跟另一个反斜杠时没有字面意义.编辑:^ 在这方面一切都按预期工作,我一定是使用了错误的 shell(在我的其他终端中使用了 tcsh,并且字符与“a”不同)。

虽然我无法找出实际发生的事情,但在寻找答案时,我遇到了一些人在命令替换方面提到术语“引用上下文”,但没有解释它是什么意思或描述的地方。我没有在 Bash 引用资料(gnu.org、tldp、man bash)中或通过 DuckDuckGo 找到任何对“引用上下文”的真正引用。

除了了解正在发生的事情之外,我更希望获得一些关于如何从中辨别出这种行为的引用或指导,因为我认为我可能没有将一些自然产生的部分组合在一起.否则我会忘记答案。

致那些建议人们使用新型美元符号和圆括号替换的人:关于 ca。 50 年前的 Unix 机器拥有数十或数百种不同的专有环境(不能为更新的环境扔掉一个 shell),当必须编写在任何人可能使用的大多数 shell 之间兼容的脚本时,这不是一种选择。

感谢任何能帮助我的人。

最佳答案

POSIX在 2.2.3 中有这样的说法(强调我的):

` (backquote)

The backquote shall retain its special meaning introducing the other form of command substitution (see Command Substitution). The portion of the quoted string from the initial backquote and the characters up to the next backquote that is not preceded by a <backslash>, having escape characters removed, defines that command whose output replaces "`...`" when the word is expanded. Either of the following cases produces undefined results:

  • A single-quoted or double-quoted string that begins, but does not end, within the "`...`" sequence

  • A "`...`" sequence that begins, but does not end, within the same double-quoted string

对我来说,这几乎定义了其他人可能(非正式地?)调用包含两个连续反引号中的所有内容的引用上下文

从某种意义上说,反引号是除单引号、双引号和反斜杠之外的第四个引号。请注意,在双引号内,单引号也失去了它们的引号功能,因此反引号改变了双引号内的功能也就不足为奇了。

我用其他 shell 尝试了您的示例,例如 FreeBSD 和 zsh 上的 Almquist shell。正如预期的那样,它们输出 一些路径

关于linux - 为什么反引号中的嵌套引号在 bash 中有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47803329/

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