Add vercmp function
The existing vercmp_numbers function only handles, as the name says,
numbers. I noticed that "sort" has had a version sort for a long time
[1] and, rather than re-implement it badly, use this as a version of
vercmp that works a bit more naturally.
This is intended to be used in an "if" statement as in
prog_ver=$(prog_ver --version | grep ...)
if vercmp $prog_ver "<" 2.0; then
...
fi
A test-case is added to test the basic features and some edge-cases.
[1] http://git.savannah.gnu.org/gitweb/?p=coreutils.git;a=commitdiff;h=4c9fae4e97d95a9f89d1399a8aeb03051f0fec96
Change-Id: Ie55283acdc40a095b80b2631a55310072883ad0d
diff --git a/functions b/functions
index 34da1ba..e5e3400 100644
--- a/functions
+++ b/functions
@@ -527,12 +527,58 @@
typeset v1=$1 v2=$2 sep
typeset -a ver1 ver2
+ deprecated "vercmp_numbers is deprecated for more generic vercmp"
+
IFS=. read -ra ver1 <<< "$v1"
IFS=. read -ra ver2 <<< "$v2"
_vercmp_r "${#ver1[@]}" "${ver1[@]}" "${ver2[@]}"
}
+# vercmp ver1 op ver2
+# Compare VER1 to VER2
+# - op is one of < <= == >= >
+# - returns true if satisified
+# e.g.
+# if vercmp 1.0 "<" 2.0; then
+# ...
+# fi
+function vercmp {
+ local v1=$1
+ local op=$2
+ local v2=$3
+ local result
+
+ # sort the two numbers with sort's "-V" argument. Based on if v2
+ # swapped places with v1, we can determine ordering.
+ result=$(echo -e "$v1\n$v2" | sort -V | head -1)
+
+ case $op in
+ "==")
+ [ "$v1" = "$v2" ]
+ return
+ ;;
+ ">")
+ [ "$v1" != "$v2" ] && [ "$result" = "$v2" ]
+ return
+ ;;
+ "<")
+ [ "$v1" != "$v2" ] && [ "$result" = "$v1" ]
+ return
+ ;;
+ ">=")
+ [ "$result" = "$v2" ]
+ return
+ ;;
+ "<=")
+ [ "$result" = "$v1" ]
+ return
+ ;;
+ *)
+ die $LINENO "unrecognised op: $op"
+ ;;
+ esac
+}
# This function sets log formatting options for colorizing log
# output to stdout. It is meant to be called by lib modules.