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.
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).
This example will exit to shell with exit code 1. Should you change
$v1
to1-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 thevertest()
is left as an exercise for the reader.