I want to check the version of my compiler in a Makefile and if its below some specified version then I want to do something different.
I can evaluate the version number with this (in Makefile)
isbelow := $(shell ifort --version | grep -oP -m 1 '[0-9] \.\d')
The shell command returns something like 2021.1
or 2021.5
. I want to check if that version is below 2021.5
, i.e. I want to extend the shell script so that it returns True
in case the version number is below 2021.5
. How do I do that.
CodePudding user response:
sort --version-sort
can be used in a shell script as follows:
#!/bin/sh
# $1 version
# $2 reference version
# Returns 0 if equal, -1 if older and 1 if greater.
versionCompare() {
if test "$1" == "$2"; then
printf '%d\n' 0
return
fi
greatest=$(printf "%s\n%s\n" "$1" "$2" | sort --version-sort | tail -n 1)
result=-1
if test "$greatest" == "$1"; then
result=1
fi
printf '%d\n' "$result"
}
# Checks if version $1 is older than reference version $2.
isVersionOlder() {
c="$(versionCompare "$1" "$2")"
test "$c" -lt 0
}
Usage:
version='2021.1'
referenceVersion='2021.5'
if isVersionOlder "$version" "$referenceVersion"; then
printf 'Version %s is older than %s\n' \
"$version" "$referenceVersion"
else
printf 'Version %s is greater than or equal to %s\n' \
"$version" "$referenceVersion"
fi
CodePudding user response:
Changing your make variable SHELL to SHELL=/bin/bash
, it will use bash instead of the default sh which will allow for the following commands redirection to work with awk in your script
awk '{if ($$0 < 2021.5) print "True"; else print "False"}' <<< "$isbelow"
If changing the shell is not an option, this should also work
echo "$isbelow" | awk '{if ($$0 < 2021.5) print "True"; else print "False"}'
CodePudding user response:
Well, I found a simple way myself
echo `ifort --version | grep -oP -m 1 '[0-9] \.\d'` \>= 2021.5 | bc
or to use in Makefile
isbelow := $(shell echo `ifort --version | grep -oP -m 1 '[0-9] \.\d'` \>= 2021.5 | bc)
This is a wired way to use bc
to compare the versions. This works because the version number has only one dot and won't work if there are two dots (e.g. version 7.6.5). Obviously it's not a general solution, but may be useful to some.