#!/bin/bash

# Steve Allison -- blog@nooblet.org
# http://www.nooblet.org/blog/2013/quick-disk-usage-bash-script/

function bytesToString() {
	if [ -z "$1" ] || [ "$1" -lt 1 ]; then echo "0K"; return; fi
	s=""
	n=1
	p="K"
	declare -a Pa=( K M G T P )
	for i in {5..0}; do
		p=${Pa[$i]}
		n=$((1024**${i}))
		if [ "$1" -gt "$n" ]; then break; fi
	done
	s=$(( ($1 * 10) / $n ))
	d=${s:${#s}-1}
	s=${s:0:${#s}-1}
	if [ "${s}" -lt 10 ] && [ "${d}" -gt 0 ]; then
		s="${s}.${d}"
	elif [ "${d}" -gt 4 ]; then s=$(( $s +1)); fi
	echo -n "${s}${p}"
}

total=0
declare -a a
echo -en "\rCalculating.. "
while IFS=$'\t' read -r -a a; do
	if [ "z${a[1]}z" = "z.z" ]; then
		total=${a[0]}; continue;
	fi
	if [ -z "${begin}" ]; then begin=1; echo -en "\r                 \r"; fi
	echo -e "$(bytesToString ${a[0]})\t${a[1]}"

done < <( (du -x --max-depth=1; du -S -x --max-depth=0|sed 's/\.$/[.]/')|sort -n)
echo "--"
echo -e "$(bytesToString ${total})\t[total]"
