DEV Community

Ibrahim
Ibrahim

Posted on

2 Ways to Count Files in a Linux Directory Using Bash

Counting files in a Linux directory is a common task used daily. Here are two ways to do it using Bash.

1. Using the ls and wc Commands

The ls -1 command lists directory contents one per line. Piping the output to wc -l counts the lines, giving the total number of files. Example:

ls -1 ~/Documents | wc -l
# 25
Enter fullscreen mode Exit fullscreen mode

To include hidden files (starting with .), add the -a option to ls. Example:

ls -a1 ~/Documents | wc -l
# 30
Enter fullscreen mode Exit fullscreen mode

2. Using the find and wc Commands

The find command lists all files and directories in a path recursively. Piping the output to wc -l counts the lines, giving the total number of files. Example:

find ~/Documents | wc -l
## 105
Enter fullscreen mode Exit fullscreen mode

To count files by searching for a specific name or file extension, add the -iname option.

find ~/Documents -iname "*.mp4" | wc -l
## 14

find ~/Documents -iname "*jobs*" | wc -l
## 44
Enter fullscreen mode Exit fullscreen mode

To count only files, add the -type option with the value f. Example:

find ~/Documents -type f | wc -l
## 87
Enter fullscreen mode Exit fullscreen mode

To count only directories, add the -type option with the value d. Example:

find ~/Documents -type d | wc -l
## 29
Enter fullscreen mode Exit fullscreen mode

Top comments (0)