How to Calculate Directory Sizes Using the du Command in Linux

When a Linux server’s hard drive suddenly fills up to 100% capacity, the entire operating system will crash. You cannot simply run the ls command to find the culprit, because ls only displays the size of individual text files, not massive, nested directories containing thousands of sub-folders. To recursively calculate the exact mathematical size of an entire directory tree and isolate the massive files choking your server, you must use the du (Disk Usage) command.

How the du Command Works

The du command is a highly aggressive crawler. When you point it at a directory, it dives into every single sub-folder, calculates the exact byte size of every individual file, and mathematically aggregates those numbers to give you the total weight of the directory structure.

To execute a basic scan of the massive /var/log/ directory, you would type:

du /var/log/

However, the default output is completely illegible to humans because it strictly calculates sizes in 1-Kilobyte blocks (e.g., 1504932). To force the engine to translate those massive numbers into readable Megabytes and Gigabytes, you must append the -h (Human-Readable) flag:

du -h /var/log/

Summarizing the Output

If you run du -h on a massive directory, it will print thousands of lines of text to your terminal, showing you the exact size of every single tiny sub-folder. This is usually overwhelming and useless if you only want the grand total.

To force the engine to calculate the entire directory but only print the final, aggregated grand total, you must append the -s (Summarize) flag:

du -sh /var/log/

The terminal will instantly output a single, highly readable line:

4.2G    /var/log/

This instantly tells you that the logging directory is consuming exactly 4.2 Gigabytes of space.

Isolating Massive Directories

If your entire /var/ partition is full, but you don’t know which specific sub-folder is causing the problem, you can combine du with the sort command to generate a ranked list of the largest directories.

du -h --max-depth=1 /var/ | sort -hr
  • –max-depth=1: Forces the crawler to only calculate the top-level folders inside /var/, preventing it from printing thousands of nested sub-directories.
  • sort -hr: Takes the output from du and mathematically sorts it by human-readable numbers (h) in reverse order (r), putting the absolute largest directories at the very top of your screen.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.