Home > OS >  Compare variables with unit suffixes in shell
Compare variables with unit suffixes in shell

Time:11-11

I need a help on below she’ll script

Suppose we have 2 variables which will get values dynamically in sizes byes kb me gb

Var1 = 25 mb it can be in any size either in bytes or kb or mb or gb

Var2 = 1 gb it can be in any size either in bytes or kb or mb or gb

Now I need to compare these values, if var1 size is less than var2 size then proceed else come out.

Pls help I am very new to bash scripting

I am new to shell not getting how to write this

CodePudding user response:

Match the prefix, multiply appropriately. See this running at https://ideone.com/W1vXOk

#!/usr/bin/env bash
size_re='^[[:space:]]*([[:digit:]] )[[:space:]]*([kmg]b)[[:space:]]*$'

declare -A multipliers=(
  [kb]=$(( 1024 ))
  [mb]=$(( 1024 * 1024 ))
  [gb]=$(( 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='1 gb'
Var1_bytes=$(to_bytes "$Var1") || exit
Var2_bytes=$(to_bytes "$Var2") || exit
if (( Var1_bytes > Var2_bytes )); then
  echo "Var1 is larger than Var2"
else
  echo "Var1 is not larger than Var2"
fi
  • Related