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
lswith-dto print directories:
$ ls -d */- Use
ls -Fwithgrep:
$ ls -F | grep "/$"
- Use
ls -lwithgrep:
$ ls -l | grep "^d"- Use
findto print directories:
$ find . -type d -maxdepth 1 -printHow 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...