Skip to content

Instantly share code, notes, and snippets.

@thomedes thomedes/README.md
Last active Dec 20, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.