Skip to content

Instantly share code, notes, and snippets.

@suewonjp
Last active January 7, 2017 09:28
Show Gist options
  • Save suewonjp/21679602f18d25834c967c15b7d29747 to your computer and use it in GitHub Desktop.
Save suewonjp/21679602f18d25834c967c15b7d29747 to your computer and use it in GitHub Desktop.
compare two version notation strings in Bash
#!/bin/bash
versionAccepted() {
### $1 is the minimum required version, $2 is the version in question;
### If $1 < $2, return 0 (the input version is accepted)
### otherwise, return 1 (not accepted)
versions=( "$1" "$2" )
#printf "${versions[*]}\n"
for (( i=0; i<${#versions[@]}; ++i )); do
### Make it lowercases
local v=${versions[$i],,}
### Strip off quots;
### Most of cases, it is not necessary, but
### Some tools return quoted version strings and
### the quotes may be here without being removed by the shell;
[ "${v:0:1}" = "\"" ] && v=${v#\"} && v=${v%\"}
[ "${v:0:1}" = "\'" ] && v=${v#\'} && v=${v%\'}
### [ Extension point ] Add rules to suit your version naming convension;
### [ Discussion ]
### e.g., You might expect that 1.8.0-alpha3 < 1.8.0-beta2,
### but this will be 1.8.0-alpha3 > 1.8.0-beta2
### unless you add a rule saying alpha comes before beta;
### ( Non-numerics will be ignored by default )
### So add a new rule as follows to make alpha < beta work
### v=${v/alpha/0.}; v=${v/beta/1.}
### Likewise, to make 1.8.0_0-ea < 1.8.0_0 work
### ( 'ea' stands for 'early access'; JRE/JDK uses this naming conversion )
### Add a rule as follows;
### v=${v/ea/}; v+=.
versions[$i]=${v}
done
#printf "${versions[*]}\n"
local lesserVersion=$( printf "%s\n%s" "${versions[0]}" "${versions[1]}" | tr -cs '0-9\n' '.' | sort -t . -k1,1 -k2,2 -k3,3 -k4,4 -k5,5 -k6,6 -k7,7 -k8,8 -k9,9 -g | head -1 )
local minimumVersion=$( printf "%s" "${versions[0]}" | tr -cs '0-9' '.' )
#printf "%s --- %s\n" "$minimumVersion" "$lesserVersion"
[ "$lesserVersion" = "$minimumVersion" ]
}
versionAccepted "$1" "$2"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment