For a bash script for comparing if one version string is greater than another, how would it be done if the version string has 2 dots ?
so how to compare than version 2.0.1 is greater than 1.9.1 ? or that 1.8.5 is less than 1.9.5
cheers
For a bash script for comparing if one version string is greater than another, how would it be done if the version string has 2 dots ?
so how to compare than version 2.0.1 is greater than 1.9.1 ? or that 1.8.5 is less than 1.9.5
cheers
You can break up a version string as follows without expensive forks to cut
or whatever. This works in all Bourne-derived shells.
$ x=11.12.13
$ first=${x%%.*} # Delete first dot and what follows.
$ last=${x##*.} # Delete up to last dot.
$ mid=${x##$first.} # Delete first number and dot.
$ mid=${mid%%.$last} # Delete dot and last number.
$ echo $first $mid $last # Voila!
11 12 13
Then compare numerically with
if test $first -gt 1; then
...
fi
You get the idea.
You could use the cut command, specifying the -d '.' option (delimiter) and -f option to choose your field. With that, you can break down each version string into components and compare as you wish.
You'll also likely want error handling, like strings with only 1 dot, and so on.
Alternatively, if your strings are particularly predictable, you could use sed to strip out dots and compare the resulting strings. That requires a lot of constraints, though, so 2.10.1 is greater than 2.3.1
Given what you have, you could also remove the dots and treat them as numbers. Something like this:
#!/bin/sh
#
v1='2.0.1'
v2='1.9.1'
nv1=`echo $v1 | sed 's/\.//g'`
nv2=`echo $v2 | sed 's/\.//g'`
if [[ nv1 -gt nv2 ]]; then
echo "$v1 > $v2"
else
echo "$v1 <= $v2"
fi
Results in:
$ ./test.sh
2.0.1 > 1.9.1