-
-
Save Vlad-CSA/612e584ad43957aa3afa81c9928e7732 to your computer and use it in GitHub Desktop.
Bash function to parse major, minor and patch versions from a semantic versioning string
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
#!/bin/bash | |
# | |
# Function that parses semantic versioning striings of | |
# the form: | |
# MAJOR.MINOR.PATCH([+-].*)? | |
# | |
# Parse the major, minor and patch versions | |
# out. | |
# You use it like this: | |
# semver="3.4.5+xyz" | |
# a=($(parse_semver "$semver")) | |
# major=${a[0]} | |
# minor=${a[1]} | |
# patch=${a[2]} | |
# printf "%-32s %4d %4d %4d\n" "$semver" $major $minor $patch | |
function parse_semver() { | |
local token="$1" | |
local major=0 | |
local minor=0 | |
local patch=0 | |
if egrep '^[0-9]+\.[0-9]+\.[0-9]+' <<<"$token" >/dev/null 2>&1 ; then | |
# It has the correct syntax. | |
local n=${token//[!0-9]/ } | |
local a=(${n//\./ }) | |
major=${a[0]} | |
minor=${a[1]} | |
patch=${a[2]} | |
fi | |
echo "$major $minor $patch" | |
} | |
function parse_semver_test() { | |
local versions=( | |
'1.2.3' | |
'1.2.4+foobar' | |
'1.2.5-alpha01' | |
'not-a-semver' # not valid | |
'2.3.4abc' # not strictly semver but it works' | |
'a1.2.3' # not valie | |
) | |
for version in ${versions[@]} ; do | |
a=($(parse_semver "$version")) | |
major=${a[0]} | |
minor=${a[1]} | |
patch=${a[2]} | |
printf "%-32s %4d %4d %4d\n" "$version" $major $minor $patch | |
done | |
} | |
parse_semver_test |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment