Linux – Disk Usage (du) Sorted by Size

Here’s a simple way to find how much disk space is taken up by each folder in a directory, and sort it by size. This works in pretty much any Linux distribution (Ubuntu, Fedora, CentOS, and more).

du --block-size=MiB --max-depth=1 | sort -n
  • du is the disk usage and will, by default, recursively traverse every directory of the current one, listing the size of the directory by bytes. Without options, it isn’t very helpful (press Ctrl C to stop the process safely)
  • –block-size=MiB will convert the bytes amount to megabytes (or Mebibytes), so instead of showing 9437184 (bytes) it will show 9 MiB
  • –max-depth=1 will only list size of directories in the current directory. 2 will traverse an additional level down, and so on.
  • | sort -n will transfer, or “pipe”,  the output of the du program to the sort utility which simple sorts lines sent to it. -n tells it to sort numerically.
  • If you want to sort in reverse order, simply change n to rn
Example output:
statik@Phenom:~/Pictures$ du --block-size=MiB --max-depth=1 | sort -n
1MiB ./icons
1MiB ./vector
1MiB ./Webcam
3MiB ./animated
3MiB ./wallpaper
8MiB ./UltraMiami
688MiB ./2010
1600MiB ./2011
2306MiB .

As you can see, when I run this command in my Pictures folder, I have 688 MB of pictures in 2010 and 1600 MB of pictures in 2011.

You can add a shortcut to the command (an “alias”) by adding this to your ~/.bashrc or ~/.bash_aliases file

alias duinfo='du --block-size=MiB --max-depth=1 | sort -n'

The next time you open a terminal you can simply type “duinfo” and it will execute the alias. Tab completion also works.

Additional Tip: the ls (directory listing) command also supports the –block-size=MiB statement. Use –block-size=KiB for kilobytes, GiB for gigabytes, and so on.

Related Article: