This is a little function I use to compare package version strings. Sometimes they can get complex with multiple different delimiters or strings in them. I cheated a bit by using sort –version-sort for the actual comparison. If you are looking for a pure bash version to compare simpler strings (e.g. compare 1.2.4 with 1.10.2), I’d suggest this stackoverflow posting.
The function takes three parameters (the version strings and the comparison you want to apply) and uses the return code to signal if the result was valid or not. This gives the function a somewhat natural feel, for example compare_version 3.2.0-113.155 “<” 3.2.0-130.145 would return true. Aside from < and > you can also use a few words like bigger/smaller, older/newer or higher/lower for comparing the strings.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | compare_version() { local versionOne="${1}" local comparision="${2}" local versionTwo="${3}" local result= local sortOpt= local returncode=1 if [[ "${versionOne}" == "${versionTwo}" ]] ; then return 3 fi case ${comparision} in lower|smaller|older|lt|"<" ) sortOpt= ;; higher|bigger|newer|bt|">" ) sortOpt='r' ;; * ) return 2 ;; esac result=($(printf "%s\n" "${versionOne}" "${versionTwo}" | sort -${sortOpt}V )) if [[ "${versionOne}" == "${result[0]}" ]] ; then returncode=0 fi return ${returncode} } # end of function compare_version |
List of return codes and meanings:
1 2 3 4 | 0: Comparison is true 1: Comparison is false 2: Did not recognize the comparison 3: Both version strings are identical |