Skip to content

Instantly share code, notes, and snippets.

@jonlabelle
Last active October 6, 2023 19:02
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jonlabelle/6691d740f404b9736116c22195a8d706 to your computer and use it in GitHub Desktop.
Save jonlabelle/6691d740f404b9736116c22195a8d706 to your computer and use it in GitHub Desktop.
Compare Semver Versions in Bash
#!/usr/bin/env bash
#
# Performs a simple semver comparison of the two arguments.
#
# Original: https://github.com/mritd/shell_scripts/blob/master/version.sh
# Snippet: https://jonlabelle.com/snippets/view/shell/compare-semver-versions-in-bash
# Gist: https://gist.github.com/jonlabelle/6691d740f404b9736116c22195a8d706
#
readonly SCRIPTNAME="$(basename "${BASH_SOURCE[0]}")"
function usage() {
echo "Usage: $SCRIPTNAME <semver1> <semver2>"
echo
echo "Options:"
echo " -h, --help Show this help message and exit."
echo
echo "Examples:"
echo "$SCRIPTNAME 1.12.1 1.0.0"
echo
}
function semver_or_die() {
local version
version="$1"
if [[ ! ${version} =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
printf >&2 'Error : %s is not a valid semver.\n' "$version"
exit 1
fi
}
function version_gt() { test "$(echo "$@" | tr " " "\n" | sort -V | head -n 1)" != "$1"; }
function version_le() { test "$(echo "$@" | tr " " "\n" | sort -V | head -n 1)" == "$1"; }
function version_lt() { test "$(echo "$@" | tr " " "\n" | sort -rV | head -n 1)" != "$1"; }
function version_ge() { test "$(echo "$@" | tr " " "\n" | sort -rV | head -n 1)" == "$1"; }
if [[ "$1" = "-h" || "$1" = "--help" ]]; then
usage
exit 0
fi
if [[ $# -eq 0 || -z $1 || -z $2 ]]; then
printf >&2 'Error : missing required arguments.\n\n'
usage
exit 1
fi
VERSION1=$1
VERSION2=$2
semver_or_die "$VERSION1"
semver_or_die "$VERSION2"
if version_gt "$VERSION1" "$VERSION2"; then
echo "$VERSION1 is greater than $VERSION2"
fi
if version_le "$VERSION1" "$VERSION2"; then
echo "$VERSION1 is less than or equal to $VERSION2"
fi
if version_lt "$VERSION1" "$VERSION2"; then
echo "$VERSION1 is less than $VERSION2"
fi
if version_ge "$VERSION1" "$VERSION2"; then
echo "$VERSION1 is greater than or equal to $VERSION2"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment