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

1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

-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

2 Comments

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

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.