linux,

Count files within directory in Linux

Sep 28, 2021 · 1 min read · Post a comment

Sometimes, for some reason we need to pull up the number of files in a certain directory. As always, this could be done in a couple of ways. Let’s go through each of them.

Prerequisites

  • Linux bash environment
  • sudo privileges

wc command

ls . | wc -l

Note(s): Do not add parameter -l to command ls, since it returns an extra line called total at the top of the list, so it’ll add up to the final result by 1. If you want to list one file per line, you could run something like:

ls -1 . | wc -l

tree command

Step 1. Install the tree command.

## Ubuntu/Debian
sudo apt-get install -y tree
## RHEL/CentOS
sudo yum install -y tree

Step 2. Run the command tree.

tree /var/log

Output:

16 directories, 67 files

Note(s): If you want to add up the hidden files and directories to the final result, add parameter -a, for instance:

tree -a /var/log

Output:

17 directories, 70 files

find command

Count number of files in a directory:

find /var/log -type f | wc -l

Count number of directories in a directory:

find /var/log -type f | wc -l

Count number of files and directories in a directory:

find /var/log | wc -l

Conclusion

If you need the recursive number of files in a directory, and you don’t want to install additional software, find command should be the best choice though. Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.