If you're using Bash or Zsh, this function will perform the calculation for you. Additionally, if -si
is the first argument, calculations are performed in SI units.
size () {
local -a units
local -i scale
if [[ "$1" == "-si" ]]
then
scale=1024
units=(B KiB MiB GiB TiB EiB PiB YiB ZiB)
shift
else
scale=1000
units=(B KB MB GB TB EB PB YB ZB)
fi
local -i unit=0
if [ -z "${units[0]}" ]
then
unit=1
fi
local -i whole=${1:-0}
local -i remainder=0
while (( whole >= $scale ))
do
remainder=$(( whole % scale ))
whole=$((whole / scale))
unit=$(( $unit + 1 ))
done
local decimal
if [ $remainder -gt 0 ]
then
local -i fraction="$(( (remainder * 10 / scale)))"
if [ "$fraction" -gt 0 ]
then
decimal=".$fraction"
fi
fi
echo "${whole}${decimal}${units[$unit]}"
}
For example:
$ size 1
1B
$ size 100
100B
$ size 999
999B
$ size 1000
1KB
$ size 4096
4KB
$ size -si 1000
1000B
$ size -si 1024
1KiB
$ size -si $(( 1 * 1024 * 1024 ))
1MiB
$ size -si $(( 1 * 1024 * 1024 - 1 ))
1023.9KiB
$ size -si $(( 1 * 1024 * 1024 + 1024 ))
1MiB
$ size -si $(( 1 * 1024 * 1024 + 1024 + 1 ))
1MiB
$ size -si $(( 1 * 1024 * 1024 + ( 1024 * 512 ) ))
1.5MiB
$ size -si $(( 1 * 1024 * 1024 + ( 1024 * 1024 ) ))
2MiB
$ size -si $(( 1 * 1024 * 1024 + ( 1024 * 1024 - 1 ) ))
1.9MiB
This is also compatible with e.g. sort -h
.
$ { size 32; size 32000; size 35 } | sort -h
32B
35B
32KB
df -h /
. Display the size of/
in a-h
uman readable format.blockdev --getsize64