Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare versions of some products in unix ksh shell?

Tags:

shell

unix

ksh

Format of versions - X.X.X.X.
Where X - number.
What is the best way to compare two versions?
I use following code:

compareVersions()
{
  VER_1=$1
  VER_2=$2

  print -R "$VER_1"| IFS=. read v1_1 v1_2 v1_3 v1_4
  print -R "$VER_2"| IFS=. read v2_1 v2_2 v2_3 v2_4

  RESULT="0"

  if [[ "${v1_1}" -lt "${v2_1}" ]]
  then
     RESULT="-1"
  elif [[ "${v1_1}" -gt "${v2_1}" ]]
  then
     RESULT="1"
  elif [[ "${v1_2}" -lt "${v2_2}" ]]
  then
     RESULT="-1"
  elif [[ "${v1_2}" -gt "${v2_2}" ]]
  then
     RESULT="1"
  elif [[ "${v1_3}" -lt "${v2_3}" ]]
  then
     RESULT="-1"
  elif [[ "${v1_3}" -gt "${v2_3}" ]]
  then
     RESULT="1"
  elif [[ "${v1_4}" -lt "${v2_4}" ]]
  then
     RESULT="-1"
  elif [[ "${v1_4}" -gt "${v2_4}" ]]
  then
     RESULT="1"
  fi

  echo "$RESULT"
}

But I do not like it - it is very straightforward.
Maybe is there much correct way to compare versions?

like image 623
Volodymyr Bezuglyy Avatar asked Aug 18 '10 10:08

Volodymyr Bezuglyy


2 Answers

Pure Bash / Ksh:

compareVersions ()
{
  typeset    IFS='.'
  typeset -a v1=( $1 )
  typeset -a v2=( $2 )
  typeset    n diff

  for (( n=0; n<4; n+=1 )); do
    diff=$((v1[n]-v2[n]))
    if [ $diff -ne 0 ] ; then
      [ $diff -le 0 ] && echo '-1' || echo '1'
      return
    fi
  done
  echo  '0'
} # ----------  end of function compareVersions  ----------
like image 139
Fritz G. Mehner Avatar answered Nov 17 '22 15:11

Fritz G. Mehner


Maybe you could use awk?

echo $VER_1 $VER2 | \
awk '{ split($1, a, ".");
       split($2, b, ".");
       for (i = 1; i <= 4; i++)
           if (a[i] < b[i]) {
               x =-1;
               break;
           } else if (a[i] > b[i]) {
               x = 1;
               break;
           }
       print x;
     }'

There isn't a perfect way to do this. As shown you could use array / loop for the numbers, also in bash.

like image 37
schot Avatar answered Nov 17 '22 15:11

schot