Vladimir Bezugliy Vladimir Bezugliy - 4 months ago 16
Bash Question

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

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?

fgm fgm
Answer

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