Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 384
thinkhy Avatar asked Nov 29 '22 15:11

thinkhy


1 Answers

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.

like image 187
Frédéric Hamidi Avatar answered Dec 06 '22 09:12

Frédéric Hamidi