Created
July 24, 2015 15:36
-
-
Save maxrimue/ca69ee78081645e1ef62 to your computer and use it in GitHub Desktop.
Compare semantic versions in pure 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
#!/bin/bash | |
# Assume we have two semantic versions that we want to compare: | |
version1=0.12.0 | |
version2=1.15.5 | |
# First, we replace the dots by blank spaces, like this: | |
version1=${version1//./ } | |
version2=${version2//./ } | |
# If you have a "v" in front of your versions, you can get rid of it like this: | |
version1=${version1//v/} | |
version2=${version2//v/} | |
# Now we have "0 12 0" and "1 15 5" | |
# So, we just need to extract each number like this: | |
patch1=$(echo $version1 | awk '{print $3}') | |
minor1=$(echo $version1 | awk '{print $2}') | |
major1=$(echo $version1 | awk '{print $1}') | |
patch2=$(echo $version2 | awk '{print $3}') | |
minor2=$(echo $version2 | awk '{print $2}') | |
major2=$(echo $version2 | awk '{print $1}') | |
# And now, we can simply compare the variables, like: | |
[ $major1 -lt $major2 ] && echo "That's true" | |
[ $minor1 -gt $minor2 ] || echo "That's wrong" |
platform::semver_compare() {
if [ -z "${1:-}" ] || [ -z "${2:-}" ]; then
return 1
fi
normalize_ver() {
local version
version="${1//./ }"
echo "${version//v/}"
}
compare_ver() {
[[ $1 -lt $2 ]] && echo -1 && return
[[ $1 -gt $2 ]] && echo 1 && return
echo 0
}
v1="$(platform::normalize_ver "${1:-}")"
v2="$(platform::normalize_ver "${2:-}")"
major1="$(echo "$v1" | awk '{print $1}')"
major2="$(echo "$v2" | awk '{print $1}')"
minor1="$(echo "$v1" | awk '{print $2}')"
minor2="$(echo "$v2" | awk '{print $2}')"
patch1="$(echo "$v1" | awk '{print $3}')"
patch2="$(echo "$v2" | awk '{print $3}')"
compare_major="$(platform::compare_ver "$major1" "$major2")"
compare_minor="$(platform::compare_ver "$minor1" "$minor2")"
compare_patch="$(platform::compare_ver "$patch1" "$patch2")"
if [[ $compare_major -ne 0 ]]; then
echo "$compare_major"
elif [[ $compare_minor -ne 0 ]]; then
echo "$compare_minor"
else
echo "$compare_patch"
fi
}
It was done using this guide for a WIP feature for https://github.com/codelytv/dotly
Thank you!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice script 👍