count files in directory

Shell Script to Count Number of Files in Directory

Sometimes you may need to count number of files in Directory. In this article, we will look at how to create shell script to count number of files in directory.


Shell Script to Count Number of Files in Directory

Here are the steps to create shell script to count number of files in directory.


1. Create empty shell script

Open terminal and create empty shell script as shown.

$ sudo vi file_count.sh


2. Add shell script

Add the following lines to your shell script.

#!/bin/sh

echo "No. of files is $(find "$@" -type f | wc -l)"
echo "No. of directories is $(find "$@" -type d | wc -l)"

Save and close the file. In the above code, the first line specifies shell environment for execution. Next we use find condition to recursively list all the files in it and its subfolders. We pipe this output to wc command to count number of lines, thereby getting count of files. We also use another find condition to recursively list all folders & subdirectories. We also pipe this output to wc command to count number of directories.


3. Make shell script executable

Run the following command to make the file executable.

$ sudo chmod +x file_count.sh


4. Test shell script

Test the shell script on various directories on your system.

$ sudo ./file_count.sh /home/data
No. of files is 150
No. of directories is 10

That’s it. In this article, we have looked at how to create shell script to count number of files in directory. The key is to use find command with options to list all the files & directories, and pass this output to wc command to count the number of lines.

Also read :

Shell Script to Count Number of Words in File
How to Enable & Disable Services in Linux
NGINX Alias vs Root
How to Download File to Directory in wget
How to Create Disk Image from Directory

Leave a Reply

Your email address will not be published.