One of the frequently used commands on Linux OS while using a command line interface (CLI) is the ls command. This command is used to list the contents of a directory, but it can also be used to list only directories. This article will discuss different methods to list only directories using the ls command in Bash, along with examples that are mentioned below.
- Using the ls -d Option
- Using the ls -F Option
- Using the ls -l option and grep Command
Method 1: Using the -d Option
The simplest way to list only directories using the ls command is to use the -d option. This option tells ls to list only the directories in the current directory and not the contents of those directories. The command to do this is as follows:
#!/bin/bash
ls -d */
Code Explanation:
- The slash (/) after the asterisk (*) is important and tells the shell to treat the asterisk as a directory wildcard, and not a file wildcard.
- The output of this command will be a list of all the directories in the current directory.
The code output can be seen by executing the bash script below:
$ bash list_dir.sh
Method 2: Using the -F Option
Another way to list only directories using the ls command is to use the -F option. This option tells ls to add a trailing slash (/) to the names of directories. The command to do this is as follows:
#!/bin/bash
ls -F | grep /
Code Explanation:
- The -F option adds a trailing slash (/) to the names of directories and other symbols to the names of other types of files.
- The grep command is then used to filter out the names of files that do not have a trailing slash (/).
- The output of this command will be a list of all the directories in the current directory.
The output of the code can be seen by executing the bash script mentioned below:
$ bash list_dir.sh
Method 3: Using the -l option and grep Command
The -l option of the ls command and the grep command can also be used to list only directories. The below shell script can perform this process as shown below:
#!/bin/bash
ls -l | grep "^d"
Code Explanation:
- The -l option tells ls to list the contents of directories in a long format.
- The ^d in the grep command matches the leading d in the directory permissions column.
The output of the code can be seen by executing the bash script mentioned below:
$ bash list_dir.sh
Conclusion
The ls command can be used to list directories and files both in Linux OS. But sometimes a user only wants to list the available directories to avoid confusion. In this article, three different options of the ls command have been discussed that can list only directories, which are -d, -F, and -l.