Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 922
all_techie Avatar asked Nov 25 '25 00:11

all_techie


1 Answers

If you are on a Debian system, then using dpkg is the easiest:

if dpkg --compare-versions $A lt $B
then
  # $A < $B was true
fi

It supports all six comparison operators (see man dpkg and search on compare-versions).

One potential drawback: your versions have to be Debian compatible.

like image 90
Alexis Wilke Avatar answered Nov 27 '25 14:11

Alexis Wilke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!