Bash and Linux

Top 3 directories by size

easyDisk, processes, permissions Must-do

Problem statement

/var is almost full and you need to know where the space went. On the server you ran du -sh /var/* 2>/dev/null and saved the output below (size, a tab, then the path). Print the 3 largest directories, biggest first. Note that the sizes use mixed units (K, M, G).

du.txt

TEXT
1.2G /var/lib
48K /var/mail
512M /var/log
3.4G /var/cache
8.0K /var/opt
96M /var/backups
120M /var/tmp

Examples

Example 1

Input: sort -rh du.txt | head -n 3

Output: 3.4G /var/cache 1.2G /var/lib 512M /var/log

Explanation: A plain numeric sort would rank 512M above 3.4G.

Hints

Approach

Optimal

sort -h (human-numeric) compares values with unit suffixes, so it knows 3.4G is bigger than 512M. -r reverses the order to put the biggest first, and head -n 3 keeps the top three. On a live server, the whole thing is one pipeline: du -sh /var/* prints one summarised (-s) human-readable (-h) total per entry, and 2>/dev/null hides Permission denied noise. Add -x to du to avoid descending into other mounted filesystems.

Bash
# On a live server:
# du -sh /var/* 2>/dev/null | sort -rh | head -n 3
# Against the saved output:
sort -rh du.txt | head -n 3

Follow-up questions

  • du and df disagree on used space. What are the usual causes? (deleted-but-open files, reserved blocks, mounts hidden under a directory)
  • How would you drill down interactively? (ncdu, or du -h --max-depth=1)

Frequently asked questions

-n reads only the leading number and ignores the unit, so 512M (512) sorts above 3.4G (3.4). Either use sort -h with du -h, or have du print plain kilobytes with du -sk and sort with -n, converting to human units only for display.