tags:

views:

52

answers:

2

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?

+2  A: 

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.

schot
+3  A: 

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  ----------
fgm
+1 You should make all your variables local though.
Dennis Williamson
You are right. Just fixed.
fgm