Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Shell script to compare 2 variables of different size

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading