Listing only directories – alternative methods
Listing only directories via scripting can be deceptively difficult. This recipe is worth knowing since it introduces multiple ways of listing only directories with various useful techniques.
Getting ready
There are multiple ways of listing directories only. When you ask people about these techniques, the first answer that they would probably give is dir
. However, the dir
command is just another command like ls
, but with fewer options. Let us see how to list directories.
How to do it...
There are several ways in which directories in the current path can be displayed:
Using
ls
with-l
to print directories:$ ls -d */
Using
ls -F
withgrep
:$ ls -F | grep "/$"
Using
ls -l
withgrep
:$ ls -l | grep "^d"
Using
find
to print directories:$ find . -type d -maxdepth 1 -print
How it works...
When the -F
parameter is used with ls
, all entries are appended with some type of file characters such as @
, *
, |
, and so on. For directories, entries are appended with...