Last active
August 29, 2015 13:57
-
-
Save Miciah/9613751 to your computer and use it in GitHub Desktop.
version_comp
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
function zeropadl () { | |
result="$1" | |
while [[ ${#result} -lt $#2 ]] | |
do | |
result="0$result" | |
done | |
echo -n "$result" | |
} | |
function zeropadr () { | |
result="$1" | |
while [[ ${#result} -lt $#2 ]] | |
do | |
result="${result}0" | |
done | |
echo -n "$result" | |
} | |
function version_comp () { | |
if [[ $1 == $2 ]] | |
then | |
return 0 | |
fi | |
# setting the field seperator to . allows us to chop the segments up | |
# easily. | |
local IFS=. | |
local i ver1=($1) ver2=($2) | |
# Handle the case where ver2 has more segments than ver1 by padding with | |
# zeros | |
for ((i=${#ver1[@]}; i<${#ver2[@]}; i++)) | |
do | |
ver1[i]=0 | |
done | |
# Pad the initial segment of each version with leading zeros. | |
ver1[0]="$(zeropadl "${ver1[0]}" $((${#ver1[0]}+${#ver2[0]})))" | |
ver2[0]="$(zeropadl "${ver2[0]}" $((${#ver1[0]}+${#ver2[0]})))" | |
# Pad subsequent segments of each version with trailing zeros. | |
for ((i=1; i<${#ver1[@]}; i++)) | |
do | |
ver1[$i]="$(zeropadr "${ver1[$i]}" $((${#ver1[$i]}+${#ver2[$i]})))" | |
ver2[$i]="$(zeropadr "${ver2[$i]}" $((${#ver1[$i]}+${#ver2[$i]})))" | |
done | |
for ((i=0; i<${#ver1[@]}; i++)) | |
do | |
# Handle the case where ver1 is has more segments than ver2 | |
if [[ -z ${ver2[i]} ]] | |
then | |
ver2[i]=0 | |
fi | |
# Compare lexicographically. | |
if [[ ${ver1[i]} > ${ver2[i]} ]] | |
then | |
return 1 | |
fi | |
if [[ ${ver1[i]} < ${ver2[i]} ]] | |
then | |
return 2 | |
fi | |
done | |
return 0 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment