“ls *”命令的输出不一致。

4

对于命令"ls *"的输出我感到困惑。我在Ubuntu 11.10和Redhat Enterprise 6.3上测试了以下场景,并得到了相同的结果。

Shell日志

$ uname -a
   Linux 2.6.32-279.19.1.el6.x86_64 #1 SMP Sat Nov 24 14:35:28 EST 2012 x86_64 x86_64 x86_64 GNU/Linux
$ echo $0
   -bash
$ cd test
$ ls
$ ls *             *<== at first, no file/directory under current work directory*
ls: cannot access *: No such file or directory
$ mkdir abc        *<== create a new directory "abc"*
$ ls *             *<== output of "ls *" is empty but directory "abc" has been created.*
$ mkdir abcd       *<== create the second directory "abcd"*
$ ls *             *<== at this point, all the directories("abc" and "abcd") are displayed.*
abc:

abcd:

有人能解释一下为什么在创建了目录 "abc" 后,"ls *" 的输出为空吗?谢谢。
3个回答

11

这主要是因为glob模式是由shell而不是ls本身扩展的。

因此,在创建一个空的abc目录后,执行以下命令:

$ ls *

执行该命令等同于手动输入以下命令ls

$ ls abc

列出abc的内容。由于abc为空,所以不会打印任何内容。

同样地,在创建abcd之后,输入:

$ ls *

执行该命令等同于手动输入 ls 命令:

$ ls abc abcd

由于传递了两个目录,ls 命令会在列出其(空)内容之前,将它们每个都作为标题打印出来。


6
因为ls *打印的是空目录abcd中的内容,所以你在输出中看不到任何内容。ls *会打印当前目录下所有文件和所有目录的内容。请尝试使用ls命令。
ls -d *

这将在输出中显示abcd

来自man ls

-d      Directories are listed as plain files (not searched recursively).

6

以下内容可能无法解决您的问题,但涉及*:no such file错误。

当bash shell选项nullglob未设置时,如果通配符扩展为没有文件,则shell会将通配符视为普通字符串。

$ ls
$ ls *
ls: cannot access *: No such file or directory

因为没有文件,所以shell将*视为普通字符串。

打开nullglob选项,shell将通配符替换为空:

$ shopt -s nullglob
$ ls *
$

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接