Created
August 16, 2019 08:34
-
-
Save butuzov/28e1c3d24a8c29ff5b1766e57dfb2e48 to your computer and use it in GitHub Desktop.
(bash) Compare Version in `Major.Minor.Patch`
This file contains hidden or 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
# Compare two versions, in version format Major.Minor.Patch | |
# It doesn't validate version format, only compare values. | |
# | |
# Usage : | |
# version_compare <compared> <required> | |
# | |
# Example: | |
# version_compare 0.13.1 0.11.0 | |
# | |
# returns | |
# -1 if compared version below (older) then version required | |
# 0 if compared version same as required | |
# 1 if compared version above (newer) then version required | |
version_compare () { | |
ver_cmp=$1 # version compared | |
ver_req=$2 # version required | |
EXAMPLE="version_compare <compared> <required>" | |
if [[ -z $ver_cmp ]]; then | |
>&2 printf "Error:\n\tCompared version not found\n" | |
>&2 printf "Usage:\n\t${EXAMPLE}\n" | |
exit 1; | |
fi | |
if [[ -z $ver_req ]]; then | |
>&2 printf "Error:\n\tRequired version not found\n" | |
>&2 printf "Usage:\n\t${EXAMPLE}\n" | |
exit 2; | |
fi | |
recent=$(echo -e "$ver_cmp\n$ver_req" | sort -nr | head -1) | |
if [[ $recent == $ver_req ]] && [[ $recent != $ver_cmp ]]; then | |
# case 1 - compared version is old one. | |
echo -1 | |
exit 0 | |
elif [[ $recent == $ver_cmp ]] && [[ $recent != $ver_req ]]; then | |
# case 2 - compared version is a newer. | |
echo 1 | |
exit 0 | |
elif [[ $recent == $ver_cmp ]] && [[ $recent == $ver_req ]]; then | |
# case 3 - versions are same. | |
echo 0 | |
exit 0 | |
else | |
exit 3 | |
fi | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment