How to compare a program's version in a shell script?
I don't know if it is beautiful, but it is working for every version format I know.
#!/bin/bash
currentver="$(gcc -dumpversion)"
requiredver="5.0.0"
if [ "$(printf '%s\n' "$requiredver" "$currentver" | sort -V | head -n1)" = "$requiredver" ]; then
echo "Greater than or equal to ${requiredver}"
else
echo "Less than ${requiredver}"
fi
(Note: better version by the user 'wildcard': https://unix.stackexchange.com/users/135943/wildcard , removed additional condition)
Shorter version:
version_greater_equal()
{
printf '%s\n%s\n' "$2" "$1" | sort -V -C
}
version_greater_equal "${gcc_version}" 8.2 || die "need 8.2 or above"
Here I give a solution for comparing Unix Kernel versions. And it should work for others such as gcc. I only care for the first 2 version number but you can add another layer of logic. It is one liner and I wrote it in multiple line for understanding.
check_linux_version() {
version_good=$(uname -r | awk 'BEGIN{ FS="."};
{ if ($1 < 4) { print "N"; }
else if ($1 == 4) {
if ($2 < 4) { print "N"; }
else { print "Y"; }
}
else { print "Y"; }
}')
#if [ "$current" \< "$expected" ]; then
if [ "$version_good" = "N" ]; then
current=$(uname -r)
echo current linux version too low
echo current Linux: $current
echo required 4.4 minimum
return 1
fi
}
You can modify this and use it for gcc version checking.