How to list only directories in Linux ?
In this quick tip, we will check how to list only directories on some path say /root.
By default, ls command displays all files and directories.
Suppose we want to see only directories then we can use this trick.
1. Default Long List “ls -l” command.
[root@nglinux ~]# ls -l | more total 886212 -rw-r--r--. 1 root root 4096 Jan 15 07:56 6511aba475c4212fd99e06f7a8baec3a.png -rw-------. 1 root root 3366 Nov 14 08:23 anaconda-ks.cfg -rw-r--r--. 1 root root 0 Jan 16 06:24 bigfile2.txt -rw-r--r--. 1 root root 2 Jan 16 06:24 bigfile.txt -r--r--r--. 1 root root 14 Mar 28 2017 Centos_BuildTag drwxr-xr-x. 2 root root 4096 Dec 14 22:36 Desktop drwxr-xr-x. 2 root root 4096 Jan 15 03:34 dir1 drwxr-xr-x. 2 root root 4096 Nov 14 08:57 Documents drwxr-xr-x. 2 root root 4096 Nov 14 08:57 Downloads -rwxr-xr-x. 1 root root 131 Jan 3 01:31 edit_host.sh -rw-r--r--. 1 root root 6 Jan 20 02:39 file -rw-r--r--. 1 root root 4096 Jan 15 08:04 file1
2. Using grep: List only directories
[root@nglinux ~]# ls -l | grep ^d drwxr-xr-x. 2 root root 4096 Dec 14 22:36 Desktop drwxr-xr-x. 2 root root 4096 Jan 15 03:34 dir1 drwxr-xr-x. 2 root root 4096 Nov 14 08:57 Documents drwxr-xr-x. 2 root root 4096 Nov 14 08:57 Downloads drwxr-xr-x. 2 root root 4096 Jan 22 03:37 hello drwxr-xr-x. 2 root root 4096 Nov 14 08:57 Music drwxr-xr-x. 2 root root 4096 Nov 14 08:57 Pictures drwxr-xr-x. 2 root root 4096 Nov 14 08:57 Public drwxr-xr-x. 2 root root 4096 Nov 14 08:57 Templates drwxr-xr-x. 3 root root 4096 Dec 29 03:01 test drwxr-xr-x. 2 root root 4096 Jan 20 02:54 testdir drwxr-xr-x. 2 root root 25985024 Jan 4 03:07 testing drwxr-xr-x. 2 root root 4096 Nov 14 08:57 Videos [root@nglinux ~]#
3. Using awk: List only directories
[root@nglinux ~]# ls -l | awk '/^d/{print}' drwxr-xr-x. 2 root root 4096 Dec 14 22:36 Desktop drwxr-xr-x. 2 root root 4096 Jan 15 03:34 dir1 drwxr-xr-x. 2 root root 4096 Nov 14 08:57 Documents drwxr-xr-x. 2 root root 4096 Nov 14 08:57 Downloads drwxr-xr-x. 2 root root 4096 Jan 22 03:37 hello drwxr-xr-x. 2 root root 4096 Nov 14 08:57 Music drwxr-xr-x. 2 root root 4096 Nov 14 08:57 Pictures drwxr-xr-x. 2 root root 4096 Nov 14 08:57 Public drwxr-xr-x. 2 root root 4096 Nov 14 08:57 Templates drwxr-xr-x. 3 root root 4096 Dec 29 03:01 test drwxr-xr-x. 2 root root 4096 Jan 20 02:54 testdir drwxr-xr-x. 2 root root 25985024 Jan 4 03:07 testing drwxr-xr-x. 2 root root 4096 Nov 14 08:57 Videos [root@nglinux ~]#
There are many ways to achieve a small task in Linux bash shell.
You may use any of the ways convenient to use.