3

I'm writing a shell script that has to know if a certain program version is less or equal to version x.xx.xx

here is an example script to try and explain what I want to do:

#!/bin/bash

APPVER="some command to output version | grep x.xx*"

if [[ "$APPVER" is smaller or equal to "x.xx*" ]]; then do something else do something else fi

is there a way to do that? I found ways to compare numbers, but they won't work with version numbers. I need a solution that uses no or as little as possible programs.

any help is appreciated!

2 Answers2

3

In bash, you can do it with printf -v:

vercomp(){
   local a b IFS=. -; set -f
   printf -v a %08d $1; printf -v b %08d $3
   test $a "$2" $b
}

if vercomp 2.50.1 < 2.6; then echo older else echo newer fi

  • can you explain what exactly your code is doing please? – Itai Nelken Feb 03 '21 at 07:32
  • It implements a bash function which compares two version strings, without using external commands like sort or spawning subprocesses with $(...). It's limited to plain version strings like 5.8.12 or 12.3.08.1; it will not work with 2.5.3-alpha1 or version/patchlevel combos. It's also bash-only, it doesnt't work with a standard shell. –  Feb 03 '21 at 10:49
  • this answer helped me a lot, but I'm marking the other one as the answer because its simpler. in real world usage this answer is more useful though. – Itai Nelken Feb 04 '21 at 19:46
3

If you have GNU sort, use its version comparison mode.

if { echo "$APPVER"; echo "x.y.z"; } | sort --version-sort --check; then
  echo "App version is x.y.x or less"
fi
  • when testing your code like this:
    APPVER="1.13"
    
    if { echo "$APPVER"; echo "1.12.9"; } | sort --version-sort --check; then
      echo "App version is 1.12.9 or less"
    fi
    

    I get this error: sort: -:2: disorder: 1.12.9 but it works when using it like this:

    APPVER="1.12.2"
    
    if { echo "$APPVER"; echo "1.12.9"; } | sort --version-sort --check; then
      echo "App version is 1.12.9 or less"
    fi
    

    do you know why?

    – Itai Nelken Feb 03 '21 at 07:31
  • 1.13 isn't 1.12.9 or less, but 1.12.2 is, so what's the problem? – Gilles 'SO- stop being evil' Feb 03 '21 at 09:46
  • I think I found what was wrong, there is no else so I got a error, your script worked perfectly fine, Thanks! – Itai Nelken Feb 03 '21 at 11:16