#!/bin/sh
#
# Format bytes into human readable form.
# Written by Peter Postma <peter@pointless.nl>
#
# This code is hereby donated to the public domain.
#

human_readable()
{
	names="kMGTPE"
	bytes=$1
	count=0

	result=`echo $bytes | awk '{if ($1 < 1024) print 1; else print 0}'`
	if [ $result -eq 1 ]; then
		echo "$bytes B"
		return
	fi

	while true; do
		bytes=`echo $bytes | awk '{print ($1 / 1024)}'`
		count=$(($count + 1))

		result=`echo $bytes | awk '{if ($1 < 1024) print 1; else print 0}'`
		if [ $result -eq 1 ]; then
			echo "$bytes $(echo $names | cut -c $count)B"
			break
		fi
	done
}

human_readable $1

