Home / List directories only with ls

List directories only with ls

The ls command is used to list directory contents when using the bash shell (and other shells), and has a variety of flags to choose what to display and how to format. This post shows how to list just the directories using ls.

Use the -d flag

Let's say we have the following directory at /tmp/test with three files and three directories:

$ ls -l
drwxr-xr-x 2 chris 1000 4096 Oct 13 09:55 1
-rw-r--r-- 1 chris 1000    0 Oct 13 09:55 1.txt
drwxr-xr-x 2 chris 1000 4096 Oct 13 09:55 2
-rw-r--r-- 1 chris 1000    0 Oct 13 09:55 2.txt
drwxr-xr-x 2 chris 1000 4096 Oct 13 09:55 3
-rw-r--r-- 1 chris 1000    0 Oct 13 09:55 3.txt

 Doing ls -ld /tmp/test will only show /tmp/test:

$ ls -ld /tmp/test
drwxr-xr-x 5 chris 1000 4096 Oct 13 09:55 /tmp/test

Adding /*/ to the end of the directory will then show the subdirectories:

$ ls -ld /tmp/test/*/
drwxr-xr-x 2 chris 1000 4096 Oct 13 09:55 /tmp/test/1/
drwxr-xr-x 2 chris 1000 4096 Oct 13 09:55 /tmp/test/2/
drwxr-xr-x 2 chris 1000 4096 Oct 13 09:55 /tmp/test/3/

If you leave the trailing slash off, then it will show the files as well as directories. To just show the subdirectories of the current directory instead of passing a full path, query */ like so:

$ ls -ld */
drwxr-xr-x 2 chris 1000 4096 Oct 13 09:55 1/
drwxr-xr-x 2 chris 1000 4096 Oct 13 09:55 2/
drwxr-xr-x 2 chris 1000 4096 Oct 13 09:55 3/

Note that I've used the -l flag in the above examples to show the file information, but you can also do it without, e.g.: ls -d */

On a Mac

The above example output was done on Debian Linux; I've noticed on my Mac there's an extra trailing slash at the end in the directory list:

ls -ld */
drwxr-xr-x  2 chris  wheel  68 13 Oct 10:01 1//
drwxr-xr-x  2 chris  wheel  68 13 Oct 10:01 2//
drwxr-xr-x  2 chris  wheel  68 13 Oct 10:01 3//

Unfortunately this seems unavoidable, because doing "ls -ld *" will show the files too. Another possibility to not show the trailing slash, if it bothers you, is to pipe an ls -l result through grep. This will be slower if it's a large directory:

ls -l | grep ^d
drwxr-xr-x  2 chris  wheel  68 13 Oct 10:01 1/
drwxr-xr-x  2 chris  wheel  68 13 Oct 10:01 2/
drwxr-xr-x  2 chris  wheel  68 13 Oct 10:01 3/

Other suggestions

If you have any other suggestions, please leave them in the comments below.