#!/usr/bin/env bash
size_re='^[[:space:]]*([[:digit:]]+)[[:space:]]*([kmg])b?[[:space:]]*$'
declare -A multipliers=(
[k]=$(( 1024 ))
[m]=$(( 1024 * 1024 ))
[g]=$(( 1024 * 1024 * 1024 ))
)
to_bytes() {
result=$1
if [[ $1 =~ $size_re ]] && { units=${BASH_REMATCH[2]}; [[ $units && ${multipliers[$units]} ]]; }; then
result=$(( ${BASH_REMATCH[1]} * ${multipliers[${BASH_REMATCH[2]}]} ))
elif (( $1 )); then
result=$(( $1 ))
else
echo "ERROR: $1 could not be parsed as a number" >&2
return 1
fi
echo "$result"
}
Var1='25 MB'
Var2=1G
Var1_bytes=$(to_bytes "${Var1,,}") || exit
Var2_bytes=$(to_bytes "${Var2,,}") || exit
if (( Var1_bytes > Var2_bytes )); then
echo "Var1 (${Var1_bytes} bytes) is larger than Var2 (${Var2_bytes} bytes)"
else
echo "Var1 (${Var1_bytes} bytes) is NOT larger than Var2 (${Var2_bytes} bytes)"
fi
IyEvdXNyL2Jpbi9lbnYgYmFzaApzaXplX3JlPSdeW1s6c3BhY2U6XV0qKFtbOmRpZ2l0Ol1dKylbWzpzcGFjZTpdXSooW2ttZ10pYj9bWzpzcGFjZTpdXSokJwoKZGVjbGFyZSAtQSBtdWx0aXBsaWVycz0oCiAgW2tdPSQoKCAxMDI0ICkpCiAgW21dPSQoKCAxMDI0ICogMTAyNCApKQogIFtnXT0kKCggMTAyNCAqIDEwMjQgKiAxMDI0ICkpCikKCnRvX2J5dGVzKCkgewogIHJlc3VsdD0kMQogIGlmIFtbICQxID1+ICRzaXplX3JlIF1dICYmIHsgdW5pdHM9JHtCQVNIX1JFTUFUQ0hbMl19OyBbWyAkdW5pdHMgJiYgJHttdWx0aXBsaWVyc1skdW5pdHNdfSBdXTsgfTsgdGhlbgogICAgcmVzdWx0PSQoKCAke0JBU0hfUkVNQVRDSFsxXX0gKiAke211bHRpcGxpZXJzWyR7QkFTSF9SRU1BVENIWzJdfV19ICkpCiAgZWx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