A friend asked the other day if there is any easy way to list all the sub-directories of the current directory on a Unix, Linux, or Mac OS X system. The answer is yes, all you have to do is this:
ls -al | grep '^d'
This ls command works by first generating a long list (the -l
option) of all files (-a
) in the current directory, then uses the grep command to only show those lines that begin with the letter 'd' (the ^d
portion of the command, where the ^
portion in particular means "line begins with").
This works because directories on Unix/Linux systems are always listed with the letter 'd' in the first column.
In the home directory on my Mac the output from this command look like this:
drwxr-xr-x 53 al al 1802 Jul 13 12:49 . drwxrwxr-t 6 root admin 204 Jul 2 18:13 .. drwx------ 11 al al 374 Jul 12 21:35 .Trash drwx------ 43 al al 1462 Jul 12 21:35 Desktop drwx------ 14 al al 476 May 12 20:07 Documents drwxr-xr-x 8 al al 272 Feb 25 17:29 GarageBandProjects drwx------ 34 al al 1156 Mar 25 10:07 Library drwx------ 4 al al 136 Dec 28 2006 Movies drwx------ 8 al al 272 Dec 28 2006 Music drwx------ 106 al al 3604 Jul 11 10:59 Pictures drwxr-xr-x 5 al al 170 Apr 1 2006 Public drwxr-xr-x 12 al al 408 Jun 30 22:48 Reference drwxr-xr-x 20 al al 680 Jul 10 17:32 Sites drwxr-xr-x 13 al al 442 Jul 1 18:25 Xfer drwxr-xr-x 6 al al 204 Mar 18 12:17 bin
I've trimmed a few directories off the list to keep it short, but you get the idea. As you can see from the first column (beginning with "drwx
"), each row that is printed is really a directory.