简体   繁体   English

为什么glob ='*'; 回声“ $ glob”只写一个“ *”,而不是文件列表?

[英]Why does glob='*'; echo “$glob” write only a '*', and not a list of files?

My question is about the shell and globbing. 我的问题是关于外壳和球的问题。

When doing something like : 当做类似的事情时:

myglob=*
echo $myglob

I get the file list of the directory, so it's ok 我得到目录的文件列表,这样就可以了

But when i do a : 但是当我做一个:

myglob=*
echo "$myglob"
*

I got the * instead of the files in the directory. 我得到的是*而不是目录中的文件。 What i don't understand, doesnt the shell pass the * to the echo command ? 我不明白,shell不会将*传递给echo命令吗?

From the bash manual page on double quotes : bash手册页的双引号中

Enclosing characters in double quotes ('"') preserves the literal value of all characters within the quotes, with the exception of '$', '`', '\\', and, when history expansion is enabled, '!'. 将字符括在双引号('“')中可保留引号内所有字符的字面值,但'$','`','\\'除外,并且在启用历史记录扩展功能时,会使用'!'。


The second command evaluates to: 第二条命令的计算结果为:

echo "*"

which, according to the link, does not expand. 根据链接,它不会扩展。

doesnt the shell pass the * to the echo command ? 外壳程序是否将*传递给echo命令?

Yes, that's the problem. 是的,就是这个问题。

echo just writes out what you pass it. echo只是写出您通过它。 If you pass it a * it will always just write out a * . 如果通过* ,它将始终只写出*

When you do 当你做

myglob=*
echo $myglob

Bash does not pass the * . 巴什没有通过*

Instead, bash expands the glob first, and essentially rewrites the command into echo file1 file2 file3 file4... . 取而代之的是,bash首先扩展glob,并将命令本质上重写为echo file1 file2 file3 file4... Unsurprisingly, echo then writes file1 file2 file3 file4... . 毫不奇怪, echo然后写入file1 file2 file3 file4...

doesnt the shell pass the * to the echo command ? 外壳程序是否将*传递给echo命令?

Yes, when it is enclosed inside quotes. 是的,当它用引号引起来时。 Filename expansion, globbing , is done by the shell during the line scan (not the echo command) but not when the pattern is inside quotes. 文件名扩展globbing是由外壳程序在行扫描期间完成的(不是echo命令),但是当模式在引号内时则不行。

set -x ( xtrace ) is your friend, this shows the expansions and when they happen (the leading + is the xtrace prompt, PS4 ): set -xxtrace )是您的朋友,它显示了扩展及其发生的时间(前导+xtrace提示符PS4 ):

set -x
myglob=*
echo $myglob

Gives: 得到:

+ myglob='*'
+ echo ... filenames in the current directory ...

You can see that the expansion of * is done before echo is invoked. 您可以看到*的扩展是调用echo 之前完成的。

Whereas: 鉴于:

set -x
myglob=*
echo "$myglob"

Gives: 得到:

+ myglob='*'
+ echo '*'
*

Here you can see there is no expansion, and that is one reason (there are others) for using quotes. 在这里您可以看到没有扩展,这是使用引号的一个原因(还有其他原因)。

set +x will switch the xtrace feature off. set +x将关闭xtrace功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM