Skip to content

Instantly share code, notes, and snippets.

@siutin
Last active May 24, 2017 10:04
Show Gist options
  • Select an option

  • Save siutin/3b7ad8e3409c26c6d03c6d547a0358c8 to your computer and use it in GitHub Desktop.

Select an option

Save siutin/3b7ad8e3409c26c6d03c6d547a0358c8 to your computer and use it in GitHub Desktop.
a bash script for converting human number to bytes
#!/bin/bash
INPUT=$1
PAT="^([0-9]+|([0-9]+).([0-9]+))([GgMmKk])?$"
if [[ ! $INPUT =~ $PAT ]]; then
echo "error: bad format"
exit 1
fi
VALUE=$(echo "$INPUT" | sed "s/[^0-9\.]//g")
case "$INPUT" in
*G|*g)
echo $(echo "$VALUE*1024*1024*1024" | bc);;
*M|*m)
echo $(echo "$VALUE*1024*1024" | bc);;
*K|*k)
echo $(echo "$VALUE*1024" | bc);;
*)
PAT_NUM="^[0-9]+$"
if [[ $INPUT =~ $PAT_NUM ]]; then
echo "$VALUE"
else
echo "NaN"
fi
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment