ls默认情况下,如果作为参数传递,则列出目录的内容。当你传递*给你的 shell 时,你的 shell扩展*到所有文件和目录(在当前工作目录中),然后ls接受这些参数并处理它们。因此,它列出了指定目录的内容以及当前工作目录中的文件。
在 的情况下echo,shell 扩展了*并且您不会获得目录内容,因为 echo 仅打印作为参数传递给它的内容。
您可以使用 告诉ls不显示目录的内容ls -d *。
鉴于此设置:
$ mkdir dir{1,2}
$ touch file{1..3} dir{1,2}/morefiles{1..5}
$ ls
dir1 dir2 file1 file2 file3
Run Code Online (Sandbox Code Playgroud)
传递*到 shell (bash),导致 bash 扩展*为dir1 dir2 file1 file2 file3. 使用echowith *, 将导致echo显示 shell 扩展的内容*:
$ echo *
dir1 dir2 file1 file2 file3
Run Code Online (Sandbox Code Playgroud)
但是ls,默认情况下,目录的给定参数将扩展列出目录的内容:
$ ls *
file1 file2 file3
dir1:
morefiles1 morefiles2 morefiles3 morefiles4 morefiles5
dir2:
morefiles1 morefiles2 morefiles3 morefiles4 morefiles5
$
Run Code Online (Sandbox Code Playgroud)
您既可以丢弃*的ls,或在我的回答中提到的使用(如图所示我创建的示例目录结构之后)ls -d *,而不是:
$ ls -d *
dir1 dir2 file1 file2 file3
Run Code Online (Sandbox Code Playgroud)
这将停止ls从展示的内容dir1/和dir2/。
只是为了澄清 DravSloan 的出色回答,没有任何差异。*在这两种情况下都由外壳扩展,并且在这两种情况下它都扩展为完全相同的东西。区别在于对待他们的论点的方式echo和方式ls。
echo将只打印您提供的每个参数。ls将list directory contents如手册所说。因此,在这两种情况下,shell 都会执行左边的程序(echo或ls),并且相关程序对其每个参数执行它应该做的任何事情。结果不同是因为程序不同,而不是因为*扩展不同。