Archive for February 2025
Version comparison using rpm
Posted on Thu, Feb 20, 2025 at 11:35 by Hubertus A. Haniel
I have been playing a little bit with ChatGPT and its code generators and while doing this I stumbled across this. I wrote about versiion comparison in a previos post which is sort of a common thing that keeps coming up and I have used the function that I refer to there lots of times. It seems that rpm actually has a build in function to do this which returns result codes so you can refer to this with a function like this but obviously it will not work on other platforms and it seems that this has not been available on all rpm versions but I do not know when it was introduced:
compare_rpm_versions() {
local version1="$1"
local version2="$2"
if [[ -z "$version1" || -z "$version2" ]]; then
printf "Error: Two versions must be provided\n" >&2
return 1
fi
if ! command -v rpm &>/dev/null; then
printf "Error: rpm command not found\n" >&2
return 2
fi
if rpm --eval "%{lua: print(rpm.vercmp('$version1', '$version2'))}" &>/dev/null; then
local result; result=$(rpm --eval "%{lua: print(rpm.vercmp('$version1', '$version2'))}")
case "$result" in
1) printf "%s is newer than %s\n" "$version1" "$version2"; return 0 ;;
0) printf "%s and %s are identical\n" "$version1" "$version2"; return 0 ;;
-1) printf "%s is older than %s\n" "$version1" "$version2"; return 0 ;;
*) printf "Error: Unexpected comparison result: %s\n" "$result" >&2; return 3 ;;
esac
else
printf "Error: Failed to compare versions\n" >&2
return 4
fi
}
Edited on: Wed, Jun 04, 2025 15:00Posted in HowTo (RSS), Packaging (RPM) (RSS), Shell Scripting (RSS), System - Linux (RSS)