Listing only directories - alternative methods
Listing only directories via scripting is deceptively difficult. This recipe introduces multiple ways of listing only directories.
Getting ready
g ready There are multiple ways of listing directories only. The dir
command is similar to ls
, but with fewer options. We can also list directories with ls
and find
.
How to do it...
Directories in the current path can be displayed in the following ways:
- Use
ls
with-d
to print directories:
$ ls -d */
- Use
ls -F
withgrep
:
$ ls -F | grep "/$"
- Use
ls -l
withgrep
:
$ ls -l | grep "^d"
- Use
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 character such as @
, *
, |
, and so on. For directories, entries are appended with the /
character. We use grep
to filter only entries ending with the /$
end-of-line indicator.
The first character of any line in the ls -l
output is the type of file character. For a directory...