Monday, 30 Apr 2012 [Wednesday, 2 May 2012]

I recently discovered the -h switch of GNU sort, added in the coreutils 7.5 release from Aug 20, 2009. With this switch, sort will do a numeric sort of human-readable size numbers, i.e. it will accept “42M” and “1.3G” as numbers and put them in the right order. This led to the following shell one-liner in my ~/bin:

exec du "${@--xd1}" -h | sort -h

It invokes du to print the disk space consumption of a directory tree, then sorts its output by size. If you pass any switches they will be passed on to du, else it will default to -xd1 (-x = stay on one filesystem, do not cross mountpoints; -d1 = do not print directories deeper than 1 level).

I gave this script the only name it could have – obviously, duh.

Update: turns out that the -d switch of du is even newer than sort’s -h switch. It was added for compatibility with FreeBSD in the coreutils 8.6 release from Oct 15, 2010 – prior to that it had to be spelled --max-depth, which rather complicates matters. You would have to do this:

DEFAULT=(-x --max-depth=1)
exec du "${@-${DEFAULT[@]}}" -h | sort -h

That’ll win neither beauty nor concision contests.