Created
May 16, 2017 21:33
-
-
Save karlkfi/892322c27d4f72fb8dff170beab2549b to your computer and use it in GitHub Desktop.
Compare two semantic versions in bash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# return 0 if version A >= version B using semanatic versioning | |
function semver_gte() { | |
VERISON_A="${1}" | |
VERISON_B="${2}" | |
SEMVER_PATTERN="[^0-9]*\([0-9][0-9]*\)[.]\([0-9][0-9]*\)[.]\([0-9][0-9]*\).*" | |
SEG1_A="$(echo "${VERISON_A}" | sed -e "s#${SEMVER_PATTERN}#\1#")" | |
SEG1_B="$(echo "${VERISON_B}" | sed -e "s#${SEMVER_PATTERN}#\1#")" | |
[[ ${SEG1_A} < ${SEG1_B} ]] && return 1 | |
[[ ${SEG1_A} > ${SEG1_B} ]] && return 0 | |
SEG2_A="$(echo "${VERISON_A}" | sed -e "s#${SEMVER_PATTERN}#\2#")" | |
SEG2_B="$(echo "${VERISON_B}" | sed -e "s#${SEMVER_PATTERN}#\2#")" | |
[[ ${SEG2_A} < ${SEG2_B} ]] && return 1 | |
[[ ${SEG2_A} > ${SEG2_B} ]] && return 0 | |
SEG3_A="$(echo "${VERISON_A}" | sed -e "s#${SEMVER_PATTERN}#\3#")" | |
SEG3_B="$(echo "${VERISON_B}" | sed -e "s#${SEMVER_PATTERN}#\3#")" | |
[[ ${SEG3_A} < ${SEG3_B} ]] && return 1 | |
return 0 | |
} | |
if semver_gte "${VERSION}" "0.5.0"; then | |
echo "${VERSION} >= 0.5.0" | |
else | |
echo "${VERSION} < 0.5.0" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This has a bug since integer comparisons using < and > require double parentheses. Failing test case: semver_gte "5.10.0" "5.8.0"
Fixed version
Output