How to Count the Number of Files in a Directory in Linux

When you use the ls command in Linux, it prints a list of files to the terminal. If you only have five or ten files in the directory, you can easily count them yourself. But what if you are looking at a log folder containing thousands of daily archives, or a massive dataset of images?

Counting them manually is impossible. Instead, you can combine two basic Linux commands using a “pipe” to automatically count exactly how many files exist in a directory.

The Commands You Need

To count the files, we need two separate tools:

  1. ls -1: The standard list command, but with the -1 (the number one) flag. This forces Linux to print the files in a single, vertical column, with exactly one file per line.
  2. wc -l: The “word count” command. When used with the -l (lowercase L) flag, it stops counting words and instead counts the total number of lines of text it receives.

How to Pipe Them Together

We want to take the vertical list of files generated by ls -1 and feed that text directly into the wc -l line counter. We do this using the pipe symbol (|), which is usually located above the Enter key on your keyboard.

Open your terminal, navigate to the folder you want to count, and type:

ls -1 | wc -l

Press Enter. Instead of seeing a massive list of file names scrolling past, the terminal will instantly output a single number, such as 432. This is the exact number of files (and sub-directories) sitting in the current folder.

How to Count Files Including Hidden Files

By default, the ls command ignores hidden files (files that start with a dot, like .bashrc or .env). If you want a truly accurate count of absolutely everything in the folder, you need to add the -a (all) flag.

ls -1a | wc -l

Note: Adding the -a flag will always increase your count by at least 2. This is because Linux lists the current directory (.) and the parent directory (..) as hidden items in every folder.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.

Receive our best articles and tips delivered straight to your inbox.