Search code examples
bashls

Is this a bash bug? (list directories with ls)


If I want to list all files and directories in the following directory :

[root@centos2 dir1]# tree
.
+-- dir2
    +-- coucou.txt

1 directory, 1 file

Why dir2 is not shown below? Only the file is shown.

[root@centos2 dir1]# ls -l *
total 0
-rwxr--r-- 1 root root 0 Dec  2 18:20 coucou.txt

If I copy the directory and list, they are both shown :

[root@centos2 dir1]# cp -r dir2/ dir3
[root@centos2 dir1]# tree
.
+-- dir2
¦   +-- coucou.txt
+-- dir3
    +-- coucou.txt

2 directories, 2 files

[root@centos2 dir1]# ls -l *
dir2:
total 0
-rwxr--r-- 1 root root 0 Dec  2 18:20 coucou.txt

dir3:
total 0
-rwxr--r-- 1 root root 0 Dec  5 11:34 coucou.txt

Solution

  • No, it's not a bug; it's the expected behaviour of the shell to expand * to match everything. The * is replaced by a list of arguments, one for each matching path, before the command is run.

    In your first example, ls -l *, the shell expands * to dir2, so your command is ls -l dir2. ls then just lists the contents of that directory, so you get your file coucou.txt.

    In your second example, * is expanded to two arguments, dir2 and dir3. In this case, the behaviour of ls -l is to separately list the contents of each directory.