Using Sort to List Directories by Size

If you manage a UNIX system with a large number of directories that vary in size, chances are that you’ve needed to figure out which ones are using up the most disk space. Of course if the directories are user accounts, the best way to do this is to enable quotas and use the “repquota” command. If you just have a bunch of directories, however, you can easily figure out which ones are largest by giving the correct arguments to “du” and “sort”. Here is how:

du -sk * | sort +0nr

This will display the size of all directories and sort them from largest to smallest. If you want to sort them from smallest to largest, simply remove the “r”.

du -sk * | sort +0n

If you have nested directories, you will need to incorporate foreach to recurse through and get all the directory names.

Foreach Example in tcsh

I always forget the foreach syntax. Here is a quick example that reads all the contents of a directory into an array, prints out the name of each file, runs a simple grep on it, and ends.

foreach i ( ` /bin/ls * ` )
foreach? echo $i
foreach?/bin/grep your_grep_string $i
foreach? end