Version Comparison using KSH

107 views Asked by At

I'm trying to write a function to compare the versions of the products.

my versions can be XX.XX.XX or xx-xx-xx either it's separated with "." or "-" and number of fields can be different either xx.xx or xx.xx.xx or xx.xx.xx.xx

the versions which im gonna compare will identical in delimiters and with the fields

#!/bin/ksh
set -x

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  ----------

#compareVersions "6100-09-03" "6100-09-02"
compareVersions "6100.09.03" "6100.09.02"

Please check and give me suggestions

I have tried with the below thing which i have got a other post.. but there is no luck.. hope there should some modification should be done. I have to use across platforms ( linux, solaris, AIX ) so i have preferred KSH, i have idea only in shell scripting though.

2

There are 2 answers

1
AudioBubble On

Create arrays from version strings, then loop through them comparing elements one by one and return values accordingly. The following example will compare two version strings and returns either 0 (versions are equal), 1 (the first version string is greater) or 2 (the second version string is greater).

#!/bin/ksh

function vertest {
  set -A av1 `echo $1 | sed -e 's/\'$3'/ /g'`
  set -A av2 `echo $2 | sed -e 's/\'$3'/ /g'`

  for (( i=0; i < ${#av1[@]}; i++ )) ; do
    [[ ${av1[$i]} -eq ${av2[$i]} ]] && continue
    [[ ${av1[$i]} -gt ${av2[$i]} ]] && return 1
    [[ ${av1[$i]} -lt ${av2[$i]} ]] && return 2
  done
  return 0
}

v1="2-7-2-1"
v2="1-8-0-1"

vertest $v1 $v2 '-'
exit $?

# end of file.

This example will exit to shell with exit code 1. Should you change $v1 to 1-7-2-1, it will exit to shell with exit code 2. And so on, and so forth.

The separator escaping is not complete, but this works with most reasonable separators like a period (.) and a dash (-). This, as well as parameter checking for the vertest() is left as an exercise for the reader.

0
Walter A On

When the format of both numbers is equal (leading zero as your example), you can use

compareVersions ()
{
  val1=$(echo $1| tr -d ".-")
  echo ${val1}
  val2=$(echo $2| tr -d ".-")
  echo ${val2}

  if [ ${val1} -gt ${val2} ] ; then
     echo 1
     return
  fi
  if [ ${val1} -eq ${val2} ] ; then
      echo 0
      return
  fi
  echo  '-1'
} # ----------  end of function compareVersions  ----------