How to Count the Number of Files in a Directory in Linux
Working with Linux often involves dealing with files. One common but deceptively complex task is counting the number of files in a directory.
In this blog post, we will explore three different methods for counting the number of files in a directory, each with its own benefits and nuances. Let’s get started!
Prerequisites
To follow along with the examples in this blog post, you'll need access to a Linux operating system.
For the purpose of this blog post, I'll be using Ubuntu as my Linux distribution of choice. Specifically, I will use KodeKloud’s Ubuntu playground, which lets you access a pre-installed Ubuntu operating system in just one click. Best of all, you won't need to go through the hassle of installing any additional software— everything you need is already set up and ready to use.
Create a Directory and Populate It With Files
Let's start by setting up a sample directory and filling it with different types of files for our demonstration.
First, open a terminal window. Run the following command to create a directory named demo
and then navigate into it:
mkdir demo && cd demo
Next, we'll generate five empty .txt
files, with names ranging from file1.txt
to file5.txt
. To do this, run this command:
touch file{1..5}.txt
Now, we’ll create a hidden file. In Linux, a hidden file is any file that begins with a dot ("."). Run the following command to create a hidden file named .hidden1
:
touch .hidden1
To verify that the files have been created successfully, list the contents of the demo
directory with the following command:
ls -A
Note: We use the -A
option (capital "A") with the ls
command to list all files, including hidden ones, but excluding .
and ..
, which represent the current and parent directories respectively.
The output should display the file names we’ve just created, as shown below:
Now, let's add another layer to our directory structure. Inside demo
, we'll create a directory named subdemo
and then navigate into it. To do this, run:
mkdir subdemo && cd subdemo
Within subdemo
, let's generate three empty .doc
files, named from file1.doc
to file3.doc
. Run the following command:
touch file{1..3}.doc
Finally, we'll add two hidden files named .hidden2
and .hidden3
to the subdemo
directory. Run this command to create them:
touch .hidden2 .hidden3
As we did previously, list the contents of the subdemo
directory to confirm that the files have been created:
ls -A
As shown in the output, our files have been successfully created.
We've now established a directory structure filled with a variety of files. This includes regular files, hidden files, and some that are nested within a subdirectory.
Here's a summary of what we have inside the demo
directory:
- Five regular text files named
file1.txt
throughfile5.txt
. - One hidden file named
.hidden1
. - A subdirectory named
subdemo
.
Inside the subdemo
directory, we have:
- Three regular document files named
file1.doc
throughfile3.doc
. - Two hidden files named
.hidden2
and.hidden3
.
In total, the demo
directory contains six files, one of which is hidden. The subdemo
directory contains five files, two of which are hidden.
Our setup provides a range of scenarios for counting files. It includes considerations for hidden files and nested subdirectories, making it an ideal environment for exploring different methods of file counting with Linux commands. In the following sections, we'll explore these methods.
Count the Number of Files Using ls and wc Commands in Linux
Let's explore the different scenarios we can tackle using the combination of ls
and wc
commands.
Count all files in a directory
First, ensure that you’re in the demo
directory. Then run the following command:
ls . | wc -l
The ls .
part of the command lists all the files and directories in the current directory (specified by the dot (.)). If you don't specify a directory, it defaults to the current directory.
The pipe operator (|) is used to take the output of the command on its left (in this case, "ls .") and use it as the input to the command on its right.
wc -l
is a command that counts the number of lines in the input it receives. The wc
command stands for word count
and the -l
option tells it to count lines instead of words.
So when you run ls . | wc -l
, you're listing all the files and directories in the current directory and then counting the number of lines in that output, which effectively counts the number of files and directories.
After running the above command, you’ll see an output like this:
We got an output of 6, which represents the total count of visible files and directories in the demo
directory. The command didn't include the visible files in the subdemo
directory in its count. That's because the ls
command isn't recursive by default — it only lists the files and directories in the current directory and doesn’t look into any subdirectories.
Count all files, including hidden files in a directory
If you want to count hidden files along with the visible ones, you can use the -A
option with the ls
command:
ls -A | wc -l
The -A
option instructs ls
to list all items, including those that start with a dot, which are hidden files in Linux.
After running the above command, you’ll get an output of 7, which includes 5 visible files, one hidden file, and the subdemo
directory.
Note: While it's true that the -a
option with the ls
command also displays hidden files, it includes the .
and ..
entries in its output. In the context of counting files, this can lead to an inaccurate count. The .
represents the current directory, and ..
represents the parent directory, neither of which are actual files. As a result, to get an accurate count of the files, including hidden ones, we use the -A
option. This option, standing for almost all
, excludes the .
and ..
entries from the output, thereby providing an accurate count of the files in the directory.
Count specific file types
If you want to count only files of a specific type, you can add a pattern to the ls
command. For example, to count only .txt
files, run the following command:
ls *.txt | wc -l
This command will list all .txt
files in the current directory, and wc -l
will count the number of lines in the output.
In our case, there are five files with the .txt
extension in the demo
directory. So, the output we get is 5, as shown below:
As we've seen, the combination of ls
and wc
commands lacks flexibility. It works best when used to count the number of files inside a directory that doesn't contain any subdirectories. If there are subdirectories present, the command will count each subdirectory as a single item, adding it to the total file count, which will result in an incorrect answer. This is because we're interested in counting the number of files, not directories.
Count the Number of Files Using find and wc Commands in Linux
In the previous section, we discovered how the combination of ls
and wc
commands can be effective for counting files under specific conditions. Now, we're going to explore the use of find
and wc
commands together, which provide a greater degree of flexibility in comparison.
Count all files in a directory, including subdirectories
To count all files, both visible and hidden, in a directory and its subdirectories, you can use the find
command with the -type f
option. This tells the find
command to count all types of files but not directories. Then you pipe ("|") this output to the wc -l
command, which counts the number of lines in the output. Each line corresponds to a file, giving you the total number of files.
Run the following command:
find . -type f | wc -l
You'll see an output that represents the total number of files (both visible and hidden) in the demo
directory and its subdirectory:
But what if you only want to count visible files, excluding the hidden ones? The find
command doesn't have a direct option to exclude hidden files. However, there's a workaround: you can exclude hidden files by using a pattern. Run the following command:
find . -type f ! -name ".*" | wc -l
In this command, we're adding the ! -name ".*"
segment. What this does is it tells the find
command to exclude any files that start with a dot (the hidden files).
When you run this command, the output will represent the total count of visible (non-hidden) files in the demo
directory and the subdemo
subdirectory, as shown below:
Count all files in a directory excluding subdirectories
If you want to count the files in a directory but ignore any files in its subdirectories, you can do so by using the -maxdepth
option with the find
command. This option limits the depth of directories find
searches. When -maxdepth
is set to 1, find
only looks at the current directory level.
To find the total count of both visible and hidden files in the demo
directory, run the following command:
find -maxdepth 1 -type f | wc -l
After you run the above command, you’ll get the following output:
Now, if you want to exclude hidden files from this count, you can add the ! -name ".*"
segment to your command, like so:
find . -maxdepth 1 -type f ! -name ".*" | wc -l
After running the command, you’ll get the count of the visible files in the demo
directory, excluding both hidden files and files in subdirectories, as shown below:
Count specific file types
Sometimes, you might want to count only files of a specific type. In such cases, you can use the -name
flag followed by the file extension. For instance, if you want to count only .txt
files, run this command:
find . -type f -name "*.txt" | wc -l
The output, as shown below, is the total count of .txt
files in the current directory and all its subdirectories.
Again, if you want to limit your search to the current directory, you can use the -maxdepth
flag. For instance, to find only .txt
files in the current directory, modify and run the command as follows:
find . -maxdepth 1 -type f -name "*.txt" | wc -l
Once you run the above command, you’ll get the following output, which is the total number of .txt
files in the current directory only, excluding subdirectories.
Count the Number of Files Using the tree Command in Linux
The tree
command in Linux provides an easy way to visualize the hierarchy of your directories and files, resembling a tree structure – hence the name. It's particularly useful when dealing with many nested subdirectories, as it provides a clear layout of your files. Moreover, tree
also presents a summary at the end that counts the number of directories and files.
Please note that the tree
command might not be pre-installed on all Linux distributions. To check whether tree
is available on your system, run the following command:
tree --version
As you can see, the tree
command is not installed. Run the following command to install it using the apt
package manager.
apt-get update && apt-get install tree
After confirming that tree
is installed, run the following command to view and count the files in the demo
directory and its subdirectory.
tree .
Note: The tree
command is recursive by default, which means it includes all subdirectories in its output. If you have subdirectories within your directory, tree
will include them in the count and display them in the output.
After running this command, you'll see a tree-like structure of directories and files, as shown below:
As you can see from the output, the tree
command displays both the total count of files and directories at the bottom.
Note that the tree
command does not include hidden files (those starting with a dot) in its output by default. If you want to include hidden files in the display and count, add the -a
flag to the command like this:
tree -a .
After running this command, you'll see the same kind of output, but now including hidden files:
We’ve covered three different methods for counting files in a directory in Linux. Let’s now see when to use each of these methods.
Here are two scenarios with the optimal method to use in each one:
- Counting files in a single directory without any subdirectories: In this case, assuming that you don’t need to count hidden files, you can use all three methods. However, the
tree
command is the most appropriate choice as it is a single command. If you do have to count the hidden files, then you can use either of the other two methods. - Counting files in a directory with subdirectories: In this scenario, the use of the
ls
andwc
commands is ruled out as thels
command doesn’t count files inside subdirectories. We are left with two alternatives: the combination of thefind
andwc
commands and thetree
command. Assuming that you don’t want to count hidden files and just want the total count of files across all subdirectories, then thetree
command is the most optimal choice. However, if you do need to count hidden files and also want to limit your search to specific directory depths, the combination of thefind
andwc
commands is the most suitable option.
Conclusion
In this blog post, we learned three different methods of counting the number of files in a directory in Linux: using the ls
and wc
commands, the find
and wc
commands, and the tree
command. Now that you understand the unique advantages of each command, you're well-equipped to choose the one that best suits your specific use case.
Looking to build a solid foundation in shell scripting? Check out this course from KodeKloud:
- Shell Scripts for Beginners: In this course, you'll dive into the practical world of Linux shell scripting. Regardless of your programming experience, you'll master fundamental scripting concepts such as variables, loops, and control logic. Throughout the course, you'll get plenty of hands-on experience using our comprehensive labs. Not only that, you'll also receive immediate feedback on your scripts, which will help you improve and refine them.