Highlights
- Understand why file counts matter for storage monitoring, automation, audits, performance, and data validation.
- Quick setup: create a sample directory tree (including hidden files and a subdirectory) to practice.
- Method 1 -
ls+wc: simple, non-recursive counts; use-Afor hidden files; great for flat directories. - Method 2 -
find+wc: powerful and recursive; filter with-type f, exclude hidden via! -name ".*", and limit depth with-maxdepth. - Method 3 -
tree: visual hierarchy plus automatic totals; add-ato include hidden files. - Count specific file types using patterns:
ls *.txt | wc -lorfind . -type f -name "*.txt" | wc -l. - Know the gotchas:
lscounts directories too;findis accurate for files;treeexcludes hidden files unless-a. - Choose the right tool:
- Flat dir →
ls | wc -l(or-Afor hidden). - Nested dirs/filters/hidden →
find ... | wc -l. - Quick overview + totals →
tree(add-aif needed).
- Flat dir →
- Practical DevOps uses: CI/CD checks, backup validation, log cleanup thresholds, inode/perf troubleshooting.
- Try everything instantly on KodeKloud’s Ubuntu Playground-no local setup required.
Why Counting Files in Linux Matters / Use Cases
Counting files in Linux might sound like a trivial task, but in real-world scenarios, it plays an important role in system administration, automation, and troubleshooting. Whether you’re managing servers, organizing project files, or writing scripts, knowing how to accurately count files can save you time and prevent errors.
Here are some practical reasons and use cases where counting files really matters:
1. Monitoring Storage Usage
When working on servers or cloud environments, file accumulation can quickly consume storage space. By counting files in specific directories-such as /var/log, /tmp, or application data folders-you can identify areas that need cleanup before they become a problem. For instance, finding that a log directory contains thousands of files might indicate a misconfigured logging policy.
2. Automating File Management Tasks
In scripting and automation, you often need to know the number of files to make decisions. For example, a backup script might only run if a certain number of new files are detected, or a CI/CD pipeline might verify that build artifacts were correctly generated by checking file counts before deployment.
3. Auditing and Compliance
System audits sometimes require you to verify that a specific number of files exist-especially when dealing with configuration backups, reports, or security logs. Being able to count files programmatically ensures that no required files are missing or extra files have appeared unexpectedly.
4. Performance Troubleshooting
A large number of small files can slow down file system performance, increase inode usage, and impact read/write speeds. Counting files helps you spot such issues early and take corrective actions, such as archiving or consolidating files.
5. Data Validation and Quality Checks
Developers and data engineers often rely on file counts to confirm that a process ran successfully-for example, validating that all CSV exports completed or that the expected number of image files were generated by a script.
In short, counting files isn’t just a basic Linux command-line exercise-it’s a small but powerful diagnostic skill that supports better automation, system hygiene, and reliability in day-to-day DevOps and administrative workflows.
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 demoNext, 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}.txtNow, 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 -ANote: 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 subdemoWithin subdemo, let's generate three empty .doc files, named from file1.doc to file3.doc. Run the following command:
touch file{1..3}.docFinally, we'll add two hidden files named .hidden2 and .hidden3 to the subdemo directory. Run this command to create them:
touch .hidden2 .hidden3As we did previously, list the contents of the subdemo directory to confirm that the files have been created:
ls -AAs 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.txtthroughfile5.txt. - One hidden file named
.hidden1. - A subdirectory named
subdemo.cInside thesubdemodirectory, we have: - Three regular document files named
file1.docthroughfile3.doc. - Two hidden files named
.hidden2and.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 -lThe 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 -lThe -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 -lThis 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.
Looking to build a solid foundation in shell scripting? Check out this course from KodeKloud: Shell Scripts for Beginners.

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 -lYou'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 -lIn 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 -lAfter 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 -lAfter 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 -lThe 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 -lOnce 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 treeAfter 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
treecommand 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
lsandwccommands is ruled out as thelscommand doesn’t count files inside subdirectories. We are left with two alternatives: the combination of thefindandwccommands and thetreecommand. Assuming that you don’t want to count hidden files and just want the total count of files across all subdirectories, then thetreecommand 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 thefindandwccommands is the most suitable option.
Want to master Linux and get a deep understanding of its role in DevOps? Enrol in our Linux Learning Path.

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.
More on Linux:
- How to Check Disk Space on Linux
- How to Remove a Directory in Linux
- How to Terminate, or Kill a Process in Linux (Complete Guide)
- How to List All Users in Linux
- How to Rename a Directory in Linux
- How to Unzip Files to a Specific Directory in Linux
- How to List All Groups in Linux
- How to Make a Bash Script File Executable in Linux
- How to Search Packages With Apt Search Command
FAQs
Q1: Why do some file counts differ between ls, find, and tree?
Each command has its own logic for what it considers a “file.”
lscounts both files and directories unless filtered.findcan be restricted to only files (-type f) or directories (-type d).treeincludes a summary of both but skips hidden files unless you use-a.
So, if you notice mismatched results, it’s usually because of these subtle differences in how the commands interpret “files.”
Q2: Does Linux treat hidden files differently when counting them?
Yes. Hidden files (those starting with a dot .) are ignored by default in most listing commands like ls or tree. You must explicitly include them using options such as -A (for ls) or -a (for tree). This is intentional - hidden files usually store configuration or system-related data that users don’t need to see or modify frequently.
Q3: How can I count only directories instead of files?
You can easily flip the logic with find:find . -type d | wc -l
This counts all directories, including the current one (.). If you want to exclude the current directory from the count, use:find . -mindepth 1 -type d | wc -l
This is particularly useful when auditing folder structures or managing nested projects.
Q4: Is there a way to count files modified recently (e.g., in the last 24 hours)?
Yes! You can use the find command with the -mtime option:find . -type f -mtime -1 | wc -l
This counts all files modified within the past 24 hours. It’s a handy way to check for new or updated files in backup or automation workflows.
Q5: Can I count files based on size or other properties?
Absolutely. The find command allows size-based filters too:
- Files larger than 10MB:find . -type f -size +10M | wc -l
- Files smaller than 1KB:find . -type f -size -1k | wc -l
You can combine this with -mtime or -name filters to get highly specific counts.
Q6: Why does my file count change after using commands like du or tar?
Commands such as du (disk usage) and tar (archiving) may create temporary files or alter the directory structure while running. If you re-run a count immediately after using them, you might see a different total. This isn’t an error - it’s just Linux being dynamic with its file system operations.
Q7: What’s the most efficient way to count millions of files?
For extremely large directories, traditional commands like find or ls can be slow because they traverse the entire file tree. In such cases:
- Use
fd(a modern replacement forfind) for speed. - Or, if you have root access, try:
sudo lsof | wc-l
to quickly get system-wide open file counts.
In enterprise environments, tools likeduwith--inodesor file system metrics (df -i) are used to monitor massive file counts efficiently.
Q8: Can I combine file counting with other commands, like deleting or archiving files?
Yes! Linux allows powerful one-liners for combining actions.
For example, to count and delete all .log files older than 30 days:
find . -type f -name "*.log" -mtime +30 -print -delete | wc -l
This first lists (-print), deletes (-delete), and counts (wc -l) the files - all in one command.
(Use carefully - always test without -delete first!)


Discussion