1

my case is very simple:

I am trying to compare two values:

a=0.2
b=0.1

The code that I am trying to execute is:

if [ "$a" -gt "$b" ]; then
        echo "You are running an outdated version"
fi
4
  • 3
    If you target bash, you don't need to worry about standards compliance. [[ $a > $b ]] will work fine. Otherwise you should use the sh tag, not bash. Commented Oct 12, 2021 at 15:04
  • 7
    You can't reliably do semver comparison as floats, because something like 1.2.12 is not a valid float. see: stackoverflow.com/q/4023830/1032785. Commented Oct 12, 2021 at 15:12
  • 2
    @oguzismail that compares in lexical order, not in numerical Commented Oct 12, 2021 at 15:12
  • 3
    Bash only supports integer math. See mywiki.wooledge.org/BashFAQ/022 Commented Oct 12, 2021 at 15:13

1 Answer 1

4

Assuming you want to compare version numbers, would you please try the following:

#!/bin/bash -posix

# compares version numbers
# prints 0               if $a == $b
#        positive number if $a is newer than $b
#        negative number if $a is older than $b
vercmp() {
    local a=$1
    local b=$2
    local a1=${a%%.*}           # major number of $a
    local b1=${b%%.*}           # major number of $b

    if [[ $a = "" ]]; then
        if [[ $b = "" ]]; then
            echo 0              # both $a and $b are empty
        else
            vercmp "0" "$b"
        fi
    elif [[ $b = "" ]]; then
        vercmp "$a" "0"
    elif (( 10#$a1 == 10#$b1 )); then
        local a2=${a#*.}        # numbers after the 1st dot
        if [[ $a2 = $a ]]; then
            a2=""               # no more version numbers
        fi
        local b2=${b#*.}        # numbers after the 1st dot
        if [[ $b2 = $b ]]; then
            b2=""               # no more version numbers
        fi
        vercmp "$a2" "$b2"
    else
        echo $(( 10#$a1 - 10#$b1 ))
    fi
}

Examples:

vercmp 0.2 0.1
=> 1 (positive number: the former is newer)

vercmp 1.0.2 1.0.10
=> -8 (negative number: the latter is newer)

a=0.2
b=0.1
if (( $(vercmp "$a" "$b") > 0 )); then
    echo "You are running an outdated version"
fi
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.