命令替换中的Bash引用 [英] Bash quoting within command substitution

查看:54
本文介绍了命令替换中的Bash引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难理解这一点. 以下命令扩展文件:

I am having a hard time understanding this. The following command expand files:

% echo "(echo " * " )"
(echo  foo.txt bar.txt  )

但这不是

% echo "$(echo " * " )"
 * 

星号*不加引号.两种情况下都不会发生文件泛滥吗?命令替换如何影响这种情况?

Asterisk * is unquoted. Shouldn't the file globbing happen for both cases? How does command substitution affect this case?

推荐答案

单独查看命令会很有帮助.

It's helpful to look at the commands individually.

% echo "(echo " * " )"

...只有一个引用上下文.在这里,( echo用引号引起来,*不用引号引起来,然后)用引号引起来.

...has only a single quoting context. Here, ( echo is quoted, an * is given unquoted, and then a ) is given quoted.

% echo "$(echo " * " )"

在这里,您正在执行命令替换,而内部命令具有其自己的引用上下文.具体来说,该内部命令是:

Here, you're performing a command substitution, with the inner command having its own quoting context. Specifically, that inner command is:

# the inner command for the substitution is run first
echo " * "

...正如人们所期望的那样,它发出*作为其输出.值得注意的是,由于它具有自己的引用上下文,因此内容开始时未加引号,并且仅在看到"时才被引用.

...which emits * as its output, as one would expect. Notably, because it has its own quoting context, content starts unquoted, and only becomes quoted when the "s are seen.

然后,执行替换; 因为$()在引号内,所以替换过程不会运行字符串拆分和glob扩展(如果遵循这些步骤,则会将内部命令的输出分成多个单词,并且将每个单词扩展为一个单词.

Then, the substitution is performed; because the $() is inside quotes, that substitution process does not run string-splitting and glob expansion (which, if these steps were followed, would break the output of the inner command into multiple words, and expand each word as a glob).

echo "$(echo "*")"

...因此变成...

...thus becomes...

# effectively single-quoted because we already finished running expansions
# so expansions that would be allowed in double-quotes are already finished
echo ' * '


相比之下,如果您未引用:


By contrast, if you didn't quote:

echo $(echo "*")

...将成为...

...would become...

echo *

...其行为将符合您的预期.

...which would have behavior in line with what you anticipated.

或者,反之亦然

echo "$(echo *)"

...将变得类似于

echo 'foo.txt bar.txt'

这篇关于命令替换中的Bash引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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