Compare multi-digit version numbers in bash
Trying to write a script that searches for the version of the Application then returns the value. My problem is the value is three to four intergers long (example 4.3.2).
I have searched for a while and can't find any syntax that would allow you to use a != or -ge for anything higher than a number with periods in it. Just wondering if anyone has a better way or I will just keep adding for every version release.
What I want
else if [ $version1 -ge "9.0.8" ]; then
How it is written now
vercheck=`mdls -name kMDItemVersion /Applications/iMovie.app`
version=`echo ${vercheck:17}`
version1=`echo ${version:1:5}`
[...]
else if [ $version1 = "9.0.8" ]; [ $version1 = "9.1.1" ]; then
echo "You already have this version or a higher version installed"
exit 0
I believe I adapted this slightly from http://bashscripts.org/forum/viewtopic.php?f=16&t=1248. I like it because it's fairly compact and readable.
This is optional, but desirable IMO:
if [ "$#" != "2" ]
then
echo "$0 requires exactly two arguments."
exit 2
fi
Here's the meat:
I always use $1
for "the locally installed version" and $2
for "the version I am comparing against" so if this leaves me with $? = 1
I need to update, otherwise I'm up-to-date (or even ahead):
function version { echo "$@" | awk -F. '{ printf("%d%03d%03d%03d\n", $1,$2,$3,$4); }'; }
if [ $(version $1) -gt $(version $2) ]; then
echo "$1 is newer than $2"
exit 0
elif [ $(version $1) -lt $(version $2) ]; then
echo "$1 is older than $2"
exit 1
else
echo "$1 is identical to $2"
exit 0
fi
If all you cared about was whether $1
was up to date (that is, equal to or greater than $2
) you could make it even simpler:
if [ $(version $1) -ge $(version $2) ]; then
echo "No Newer Version Available"
exit 0
fi
Any code below that will only be executed if there is a newer version available. Otherwise the script will exit cleanly at that point.
p.s.: I do this in /bin/zsh not /bin/bash but I don't think it makes a difference in this case.