Skip to content

Instantly share code, notes, and snippets.

@thomedes
Last active June 29, 2021 16:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thomedes/6209957 to your computer and use it in GitHub Desktop.
Save thomedes/6209957 to your computer and use it in GitHub Desktop.
Compare string versions in bash

version_cmp()

Simple function to (properly) compare version strings in bash

The problem

You can not do alphabetic comparison:

1.23.4 < 1.3.4 => FALSE

Usage

version_cmp  1.2.3    4.5.6
version_cmp  1.5.6.7  1.5.6

if [[ $(version_cmp $rsync_version 2.5.7) -lt 0 ]]; then
    ERROR "Invalid version of rsync. 2.5.7 or more required"
fi

(Just to keep Google happy: By Toni Homedes i Saun)

#-----------------------------------------------------------------------------
#
# Compare two version strings
#
# @param [in] a Version string to compare
# @param [in] b Version string to compare
#
# Usage:
# version_cmp 1.2.3 4.5.6
# version_cmp 1.5.6.7 1.5.6
#
# @return -1, 0 or 1
#
#-----------------------------------------------------------------------------
version_cmp() {
local a="$1" b="$2"
local -i fa fb
while true; do
fa="${a%%.*}"
fb="${b%%.*}"
((fa != fb)) && break
a="${a#$fa}"; a="${a#.}"
b="${b#$fb}"; b="${b#.}"
if [[ -z $a && -z $b ]]; then
echo 0
return
fi
done
((fa > fb)) && echo 1 || echo -1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment