Linux tip: Sort directories by size.



Sorting Directories by Size in Linux

I often need to clean-up so natually I need to list directories in the current directory, sorted by size from largest to smallest. But since I keep forgetting the command, I am putting it here so that I can remember it later.:

du -h --max-depth=1 | sort -hr
  • du -h --max-depth=1
    The du (disk usage) command is used to estimate file space usage. The -h flag makes the output human-readable (e.g., in KB, MB, GB). The --max-depth=1 option limits the depth of the directory tree that du will traverse to current directory. It passes the output to the sort command.

  • sort -hr The sort command sorts lines of text. The -h flag sorts the numbers in human-readable format, and the -r flag sorts the results in reverse order (largest to smallest).