Dec 17, 2010
Human readable and by size sorted disk usage (du) in BASH
This is a quick tip to fix a problem that has always bugged me.
When showing disk usage in a human readable form (KB, MB, GB) for each subdirectory using du -sh *, how can you properly sort it by size.
If you just want the solution here it is as “one-liner”:
1 2 3 | function duf { du -sk "$@" | sort -n | while read size fname; do for unit in k M G T P E Z Y; do if [ $size -lt 1024 ]; then echo -e "${size}${unit}\t${fname}"; break; fi; size=$((size/1024)); done; done } |
Just put this function into your ~/.bashrc to make it permanent.
The expanded code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | function duf { // get usage in KBytes and sort du -sk "$@" | sort -n | while read size fname; // loops for each size do for unit in k M G T P E Z Y; // if size<1024 we found the correct suffix if [ $size -lt 1024 ]; // display the size then echo -e "${size}${unit}\t${fname}"; // line completed break; fi; // for each sizes suffix divide by 1024 size=$((size/1024)); done; done } |
When done, you can use your new function like this: duf /*.
Jan 07, 2011 @ 10:59:50
Reminds me an old post: http://www.earthinfo.org/linux-disk-usage-sorted-by-size-and-human-readable/
Thanks for the expanded code!
Jan 25, 2011 @ 19:41:44
You’re welcome!