thinkhy
thinkhy

Reputation: 933

Outputs of "ls *" are inconsistent

Just confused about the outputs of command "ls *". I tested below scenario both in Ubuntu 11.10 and Redhat Enterprise 6.3, got the same results.

Shell log

$ 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:

Can anyone explain why output of "ls *" is empty after directory "abc" created? Thanks.

Upvotes: 4

Views: 1201

Answers (3)

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 263047

That's mainly because the glob pattern is expanded by the shell, not by ls itself.

Therefore, after creating an empty abc directory, issuing:

$ ls *

Results in ls being invoked as if you typed:

$ ls abc

Which lists the contents of abc. Since abc is empty, nothing is printed.

In the same way, after creating abcd, issuing:

$ ls *

Results in ls being invoked as if you typed:

$ ls abc abcd

And since two directories are passed, ls will print each of them as a header before listing their (empty) contents.

Upvotes: 11

glenn jackman
glenn jackman

Reputation: 247012

This does not answer your question, but addresses the *: no such file error.

When the bash shell option nullglob is unset, if a wildcard expands to no files, then the wildcard is taken literally by the shell as a plain string.

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

There are no files, so the shell treats * as a plain string.

Turn on the nullglob option and the shell will substitute the wildcard with nothing:

$ shopt -s nullglob
$ ls *
$

Upvotes: 6

anubhava
anubhava

Reputation: 785491

Because ls * is printing content of the directory abcd which is empty hence you don't see anything in the output. ls * prints all the files and content of all the directories in current directory.

Try this ls command instead:

ls -d *

which will show abcd in output.

from man ls

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

Upvotes: 6

Related Questions