Find directories with largest number of files in Linux

I needed to find the list of directories that had the largest number of files on my Linux file system, searching recursively through the filesystem.

Here's the content you can paste in a script:

#!/bin/bash

if [ $# -ne 1 ];then
  echo "Usage: `basename $0` DIRECTORY"
  exit 1
fi

echo "Wait a moment if you want a good top of the bushy folders..."

find "$@" -type d -print0 2>/dev/null | while IFS= read -r -d '' file; do
    echo -e `ls -A "$file" 2>/dev/null | wc -l` "files in:\t $file"
done | sort -nr | head | awk '{print NR".", "\t", $0}'

exit 0

Here's the output (may take a few minutes to run depending on how much needs to be searched):

oracle@soadev:/home/oracle/scripts> ./countfiles.sh /u01/oracle

Wait a moment if you want a good top of the bushy folders...
1.  135097 files in: /u01/oracle/dir1
2.  96598 files in:  /u01/oracle/dir2
3.  74119 files in:  /u01/oracle/dir3
4.  73828 files in:  /u01/oracle/dir4/dir5/dir6
5.  55183 files in:  /u01/oracle/dir7
6.  55042 files in:  /u01/oracle/dir8/dir9
7.  52089 files in:  /u01/oracle/dir10
8.  47142 files in:  /u01/oracle/dir11/dir12
9.  19893 files in:  /u01/oracle/dir13
10. 17280 files in:  /u01/oracle/dir14

References

Find directories with lots of files in
So a client of mine got an email from Linode today saying their server was causing Linode’s backup service to blow up. Why? Too many files. I laughed and then ran: # df -ihFilesystem Inodes I...