0

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

p4guru
  • 1,400
  • 2
  • 19
  • 25
  • 2
    Related: http://stackoverflow.com/questions/4023830/bash-how-compare-two-strings-in-version-format – kojiro Jun 16 '15 at 17:51

3 Answers3

2

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.

Jens
  • 69,818
  • 15
  • 125
  • 179
-1

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

donjuedo
  • 2,475
  • 18
  • 28
  • This is more of a comment than a fleshed-out answer. *How* would you use the results of `cut` to make the comparison? How would you strip the `.` with `sed` and compare the resulting strings? How would you catch errors using either proposed method? – chepner Jun 16 '15 at 17:59
  • Stackoverflow is for providing answers, as I did. It is not for doing all the work for the OP. If he asks for examples on the usage of sed or cut, I'll be happy to provide some. So far, he has not (he may already know them). My answer is not worthy of a down vote, sir. – donjuedo Jun 16 '15 at 18:41
-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
AlG
  • 14,697
  • 4
  • 41
  • 54
  • 3
    At least until you hit version `1.10.0`... i.e. this only works as long as each "component" is a single digit (or more generally, they are all the same number of digits - it could work with NN.MM.JJ, too...) – twalberg Jun 16 '15 at 18:13