bashshellawksedgrep

Comparing two version numbers in a shell script


I have a file file1 which looks as below and carries current version and expected version numbers:

CurrV:1.5.2
ExpecV:1.8.1

I want to write a bash script to compare these two values and if ExpecV>=CurrV then I should echo SUCCESS, otherwise I should echo FAILURE.

So far I have written this thing, but not sure how to proceed:

#!/bin/bash
 ## Code already written to fetch `ExpecV` and `CurrV` from `file1`
 echo $ExpecV | grep $CurrV > /dev/null
 if [ $? -eq 0 ]
    then
        echo SUCCESS
    else
        echo FAILURE
 fi

Solution

  • The question says that ExpecV>=CurrV should be treated as success, but that does not make much sense (current version older than the expected one probably breaks something) and in your comments to this answer you allude to the desired behaviour being the other way around, so that's what this answer does.

    This requires GNU sort for its -V option (version sort):

    if cmp -s <(cut -d: -f2 infile) <(cut -d: -f2 infile | sort -V); then
        echo 'FAILURE'
    else
        echo 'SUCCESS'
    fi
    

    This requires that the line with CurrV is always the first line. It extracts the parts after the colon with cut and compares the unsorted (first process substitution <(...)) to the version-sorted output (the second process substitution).

    If they are the same, i.e., the version on the second line is greater than or equal to the one on the first line, the exit status of cmp is successful and we print FAILURE; if they aren't the same, this means that the sort inverted the order and the expected version is less than the current version, so we print SUCCESS.

    The -s flag is to suppress output of cmp ("silent"); we're only interested in the exit status.


    If you have 1.5.2 and 1.8.1 already in separate variables CurrV and ExpecV, you can do something similar as follows:

    CurrV='1.5.2'
    ExpecV='1.8.1'
    printf -v versions '%s\n%s' "$CurrV" "$ExpecV"
    if [[ $versions = "$(sort -V <<< "$versions")" ]]; then
        echo 'FAILURE'
    else
        echo 'SUCCESS'
    fi
    

    This stores the two variables into versions, separated by a newline, then compares the unsorted with the sorted sequence.