[one-liner]: Calculating & Sorting Disk Usage Using du

Background

Occasionally I want to calculate how much disk space is being consumed with a directory. Here are a couple of simple yet powerful one-liners that achieve this.

Solutions

method #1

This first choice is inefficient in the sense that it basically runs du twice. Once to generate a sorted list of the directories & files by size and a 2nd time to get the directories & files in a human readable format. However it works on the widest variety of distros, since it doesn’t rely on any of the newer switches available to du.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
% du -s * | sort -rn | cut -f2- | xargs -d "\n" du -sh
53G	projects
21G	Desktop
7.2G	VirtualBox VMs
3.7G	db
3.3G	SparkleShare
2.2G	Dropbox
272M	apps
47M	incoming
14M	bin
8.6M	parking_lot
5.7M	rpmbuild
76K	task.ref.pdf
68K	vimdir.tgz
method #2

This approach makes use of a new switch -h that was added to the sort command in versions > 0.75. This approach is much faster than the above method, but won’t work on distros like CentOS 5.x.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
% du -hs * | sort -hr
53G	projects
21G	Desktop
7.2G	VirtualBox VMs
3.7G	db
3.3G	SparkleShare
2.2G	Dropbox
272M	apps
47M	incoming
14M	bin
8.6M	parking_lot
5.7M	rpmbuild
76K	task.ref.pdf
68K	vimdir.tgz

Here’s more information about the -h switch:

‘-h’
‘–human-numeric-sort’
‘–sort=human-numeric’
Sort numerically, first by numeric sign (negative, zero, or positive); then by SI suffix (either empty, or ‘k’ or ‘K’, or one of ‘MGTPEZY’, in that order; see Block size); and finally by numeric value. For example, ’1023M’ sorts before ’1G’ because ‘M’ (mega) precedes ‘G’ (giga) as an SI suffix. This option sorts values that are consistently scaled to the nearest suffix, regardless of whether suffixes denote powers of 1000 or 1024, and it therefore sorts the output of any single invocation of the df, du, or ls commands that are invoked with their –human-readable or –si options. The syntax for numbers is the same as for the –numeric-sort option; the SI suffix must immediately follow the number.

References

NOTE: For further details regarding my one-liner blog posts, check out my one-liner style guide primer.

This entry was posted in bash, one-liner, shell, Syndicated, tip, tips & tricks. Bookmark the permalink.

Comments are closed.