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
- Access to Linux bash environment
wc command
$ ls . | wc -l
Note: 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.
$ apt-get install -y tree
for Ubuntu and Debian, or
$ yum install -y tree
for RHEL / CentOS.
Step 2. Run the command tree.
$ tree /var/log
Example output:
16 directories, 67 files
Note: If you want to add up the hidden files and directories to the final result, add parameter -a, for instance:
$ tree -a /var/log
Example 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 wanna install additional software, find
command should be best choice though.
Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.