Shell Script Version Compare (vercmp)


Here is something useful. A very short shell script to compare standard version numbers of the form ##.##.## with up to four segments. It returns the difference of the first differing segment just like strcmp.

#!/bin/sh
 
expr '(' "$1" : '\([^.]*\)' ')' '-' '(' "$2" : '\([^.]*\)' ')' '|' \
    '(' "$1.0" : '[^.]*[.]\([^.]*\)' ')' '-' '(' "$2.0" : '[^.]*[.]\([^.]*\)' ')' '|' \
    '(' "$1.0.0" : '[^.]*[.][^.]*[.]\([^.]*\)' ')' '-' '(' "$2.0.0" : '[^.]*[.][^.]*[.]\([^.]*\)' ')' '|' \
    '(' "$1.0.0.0" : '[^.]*[.][^.]*[.][^.]*[.]\([^.]*\)' ')' '-' '(' "$2.0.0.0" : '[^.]*[.][^.]*[.][^.]*[.]\([^.]*\)' ')'

Update: Added zeros to deal with unbalanced version compares

, ,

  1. #1 by Kelly Beck on April 30, 2010 - 10:22 am

    Have not checked in on the blog recently; so, I just got your comment. Awesome sauce! Extra points for brevity.

  2. #2 by Petri Lehtinen on March 25, 2011 - 6:03 am

    This would be extremely useful, but it seems to fail when comparing .e.g “1.4″ and “1.4.9″

  3. #3 by A R Baboon on March 25, 2011 - 10:07 am

    Petri Lehtinen :

    This would be extremely useful, but it seems to fail when comparing .e.g “1.4″ and “1.4.9″

    Ok I think I solved that problem. I think it will work for all expected inputs of one to four positive integers tightly packed with dots.

  4. #4 by Petri Lehtinen on March 29, 2011 - 6:00 am

    Yeah, I fixed it the same way actually before reading your response. Thanks!

  5. #5 by Bryan on May 2, 2011 - 1:09 pm

    Looks like a solid string of code to me. Should be useful, thanks!

(will not be published)


Bad Behavior has blocked 128 access attempts in the last 7 days.