Last active
November 2, 2017 08:55
-
-
Save jemyzhang/6d57d6fb11fbc9323289406eaed42619 to your computer and use it in GitHub Desktop.
convert bytes to human readble size
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash -e | |
math_calc() { | |
local format="$1" | |
local equation="$2" | |
echo | awk "{printf \"$format\", $equation}" | |
} | |
convert_to_bytes() { | |
local v=$1 | |
local s=${v%%[^0-9.]*} | |
local u=${v##$s} | |
local inbytes=0 | |
case $u in | |
KB) | |
inbytes=$(math_calc "%d" "$s * 1000") | |
;; | |
MB) | |
inbytes=$(math_calc "%d" "$s * 1000 * 1000") | |
;; | |
GB) | |
inbytes=$(math_calc "%d" \ | |
"$s * 1000 * 1000 * 1000") | |
;; | |
K|KiB) | |
inbytes=$(math_calc "%d" "$s * 1024") | |
;; | |
M|MiB) | |
inbytes=$(math_calc "%d" "$s * 1024 * 1024") | |
;; | |
G|GiB) | |
inbytes=$(math_calc "%d" \ | |
"$s * 1024 * 1024 * 1024") | |
;; | |
B|"") | |
if [ -n "$s" ]; then | |
inbytes=$(printf "%d" $s) | |
fi | |
;; | |
-) | |
#special case | |
inbytes=0 | |
;; | |
*) | |
log_err "unit not support: $u" | |
;; | |
esac | |
echo $inbytes | |
} | |
convert_to_human() { | |
local v=$1 | |
local h=0 | |
local unitidx=0 | |
local unitNames=("B" "K" "M" "G" "T") | |
while true; do | |
h=$(math_calc "%.2f" "$v / 1024") | |
if expr $h \< 1.0 > /dev/null; then | |
break | |
else | |
v=$h | |
fi | |
let unitidx=unitidx+1 | |
done | |
echo ${v%%.00}${unitNames[$unitidx]} | |
} | |
convert_to_human $(expr 1024 \* 1024 \* 30 \* 30) | |
convert_to_human $(expr 1024 \* 1024 \* 30 \* 30 \* 3) | |
convert_to_human $(expr 102 \* 4) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment