You can use the following syntax in Bash to count the number of folders in a specific directory:
ls -l | grep -c ^d
This particular example will return the total count of folders in the current directory.
Here is what the various commands do:
- ls -l: Display all files and folders in current directory in list ( -l )format
- grep -c ^d: Use grep to count ( -c ) the number of items that start ( ^ ) with d
When using the ls statement in Bash, only folders will start with drwxr, so by using grep we are able to count only the items that start with the character d, which simply counts the number of folders.
The following example shows how to use this syntax in practice.
Example: How to Count Number of Folders in Specific Directory in Bash
Suppose we would like to count the number of folders in our current directory.
First, we can use the following syntax to view all items in our current directory:
ls -l
The following screenshot shows how to use this syntax in practice:

From the output we can see that the current directory contains one file:
- good_teams.txt
The current directory also contains three folders:
- nba_data
- nfl_data
- nhl_data
We can use the following syntax to return the total count of folders only:
ls -l | grep -c ^d
The following screenshot shows how to use this syntax in practice:

This returns a value of 3, which tells us that there are 3 folders in the current directory.
This matches the number of folders that we manually viewed in the previous step.
Related Tutorials
The following tutorials explain how to perform other common tasks in Bash:
Bash: How to Count Number of Files in Directory Matching a Pattern
Bash: How to Count Number of Unique Lines in File
Bash: How to Count Number of Characters in String
Bash: How to Count Number of Columns in File
