Thursday, July 6, 2017

bash : Checking if a particular version of a software is present or not

In one bash script I was writing, I was told to take certain action based on whether version 4.2 or above of a certain software is available or not.
The versioning scheme used by the software in question is major.minor.revision
So, version 3.8.0 or 4.1.6 or 4.2.1 or 5.1.3 could be present.
Doing a string comparison is writing your own invitation for disaster.
The version obtained needs to be broken into pieces, and each piece needs to be compared numerically.

#!/bin/bash
# software_version="4.1.0"
# software_version="4.2.0"
# software_version="4.5.0"
software_version="5.1.0"
# software_version="3.8.0"
echo $software_version

major=$(echo $software_version | /usr/bin/cut -d. -f1)
minor=$(echo $software_version | /usr/bin/cut -d. -f2)
echo "major = $major  and  minor = $minor"

higher_than_4_2=0

if (($major > 4)); then
    higher_than_4_2=1
else
    if (($major == 4)) && (($minor >= 2)); then
        higher_than_4_2=1
    fi
fi
if (($higher_than_4_2 == 1)); then
  echo "Software version is equals to or greater than 4.2"
else
  echo "Software version is not equals to or greater than 4.2"
fi

No comments:

Post a Comment