The ls command is commonly used to list the contents of a directory. This list includes directories and files. What about if you need list directories themselves? Let's take a look at ls -d Linux command.
What does ls -d stand for?
The ls -d command is used to list directories themselves in the list. That means the -d option tells ls to display information about the directory itself not about the contents inside it.
For example, I have a directory named Projects which contains some files and directories. The ls Projects lists files and directories in that directory whereas ls -d Projects simply returns "Projects".
ls -d Projects
To check the permissions of the directory itself run ls -ld Projects
Examples of Using ls -d
Let's look into some use cases of ls -d with examples.
List all directories in the current location
Use ls -d */ to list all directories in the current location. Where ls -d print directories without content and */ tell the shell to match all directories.
Example:
ls -d */
The output confirms only directories in the current directory are listed.
Note: if you remove / at the end ie ls -d * then it will list all files and directories.
List all hidden directories
In the previous example, it listed all directories. What about hidden directories?
Use ls -d .*/ to list all hidden directories in the current location.
Example:
ls -d .*/
The output confirms that only hidden directories in the current directory are listed.
To include both hidden directories and non-hidden directories (i.e., all directories), run:
ls -d */ .*/
Combining ls -d with Other Commands
The ls -d command can be combined with other Linux commands to perform actions specifically on directories. Let me show you a few examples.
The most common use case is to count the number of directories in a directory.
ls -d */ | wc -l
The output shows there are a total of 12 directories in the current directory. Note hidden directories are not included.
We can combine grep with ls -d to search specific patterns of directories. Examples
ls -d */ | grep i "tem"
This command searches for directories with the pattern "tem" case insensitively in the current directory.
Comments