Skip to content

Instantly share code, notes, and snippets.

@cameronhunter
Last active April 9, 2022 04:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cameronhunter/bd3d5908935dce94eeb1a2407c7a6e96 to your computer and use it in GitHub Desktop.
Save cameronhunter/bd3d5908935dce94eeb1a2407c7a6e96 to your computer and use it in GitHub Desktop.
Parse a semver string in bash using a regular expression
#!/usr/bin/env bash
##
# Get the major/minor/patch semver from a string.
#
# Author: Cameron Hunter <hello@cameronhunter.co.uk>
# License: MIT 2022
#
# Examples:
# semver v14.22.1 major → 14
# semver v14.22.1 minor → 22
# semver v14.22.1 patch → 1
# semver v14.22.1 → 14 22 1
##
function semver {
local string="${1}"
local part="${2}"
if [[ "${string}" =~ ^v?(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*) ]]; then
case "${part}" in
major) echo ${BASH_REMATCH[1]} ;;
minor) echo ${BASH_REMATCH[2]} ;;
patch) echo ${BASH_REMATCH[3]} ;;
*) echo "${BASH_REMATCH[1]}\t${BASH_REMATCH[2]}\t${BASH_REMATCH[3]}" ;;
esac
else
return 1
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment