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" ...
Get Linux Shell Scripting Cookbook - Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.