【问题标题】:Outputs of "ls *" are inconsistent“ls *”的输出不一致
【发布时间】:2013-12-28 02:14:34
【问题描述】:

只是对命令“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 *”的输出为空?谢谢。

【问题讨论】:

    标签: linux bash shell unix ls


    【解决方案1】:

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

    因此,在创建一个空的abc 目录后,发出:

    $ ls *
    

    导致ls 被调用,就像您输入了一样:

    $ ls abc
    

    其中列出了abc 的内容。由于abc 为空,因此不会打印任何内容。

    同理,创建abcd后,发出:

    $ ls *
    

    导致ls 被调用,就像您输入了一样:

    $ ls abc abcd
    

    由于传递了两个目录,ls 将在列出它们的(空)内容之前将每个目录打印为标题。

    【讨论】:

      【解决方案2】:

      这不会回答您的问题,但会解决 *: no such file 错误。

      当 bash shell 选项 nullglob 未设置时,如果通配符扩展为 no files,那么通配符将被 shell 当作纯字符串。

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

      没有文件,因此 shell 将 * 视为纯字符串。

      打开nullglob 选项,shell 将用任何内容替换通配符:

      $ shopt -s nullglob
      $ ls *
      $
      

      【讨论】:

        【解决方案3】:

        因为ls * 正在打印目录abcd 的内容,该目录为空,因此您在输出中看不到任何内容。 ls * 打印当前目录下的所有文件和所有目录的内容

        试试这个ls 命令:

        ls -d *
        

        这将在输出中显示abcd

        来自man ls

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-11-07
          • 2018-04-30
          • 2013-04-15
          • 1970-01-01
          • 1970-01-01
          • 2016-04-08
          相关资源
          最近更新 更多