Skip to content

Instantly share code, notes, and snippets.

@Ionizing
Last active December 5, 2022 13:33
Show Gist options
  • Save Ionizing/7b90f8e44668819effc827d57eb20a74 to your computer and use it in GitHub Desktop.
Save Ionizing/7b90f8e44668819effc827d57eb20a74 to your computer and use it in GitHub Desktop.
Parse the sematic version string with bash
# Let VER_STR be the version string
VER_STR="v1.14.514-rc-v1.919.810-tnok.."
# Use `sed` to extract the MAJOR, MINOR, PATCH number
echo $VER_STR | sed -nE 's/^v([0-9]+).([0-9]+).([0-9]+)(.*)$/\1 \2 \3/p'
# prints "1 14 514"
# Convert "1 14 514" to an array of ["1", "14", "514"]
VER=($(echo $VER_STR | sed -nE 's/^v([0-9]+).([0-9]+).([0-9]+)(.*)$/\1 \2 \3/p'))
echo ${VER[0]} # prints 1
echo ${VER[1]} # prints 14
echo ${VER[2]} # prints 514
# Finally assign the MAJOR, MINOR, PATCH number to corresponding variables
VERSION_MAJOR=${VER[0]} # 1
VERSION_MINOR=${VER[1]} # 14
VERSION_PATCH=${VER[2]} # 514
# If the version string is incomplete
echo "v1" | sed -nE 's/^v([0-9]+)(.([0-9]+)(.([0-9]+))?)?(.*)$/\1 \3 \5/p'
# prints 1
echo "v1.13" | sed -nE 's/^v([0-9]+)(.([0-9]+)(.([0-9]+))?)?(.*)$/\1 \3 \5/p'
# prints 1 13
echo "v1.a" | sed -nE 's/^v([0-9]+)(.([0-9]+)(.([0-9]+))?)?(.*)$/\1 \3 \5/p'
# prints 1
echo "v1...." | sed -nE 's/^v([0-9]+)(.([0-9]+)(.([0-9]+))?)?(.*)$/\1 \3 \5/p'
# prints 1
# no leading 'v' would cause match failure
echo "1.14.514" | sed -nE 's/^v([0-9]+)(.([0-9]+)(.([0-9]+))?)?(.*)$/\1 \3 \5/p'
# prints nothing (match failed)
# empty string
echo "" | sed -nE 's/^v([0-9]+)(.([0-9]+)(.([0-9]+))?)?(.*)$/\1 \3 \5/p'
# print nothing (match failed
# makefile version
GIT_HASH := $(shell git describe --match=nEvErMaTcH --always --abbrev=8 --dirty)
GIT_VERSION := $(shell git describe --dirty --always --tags | sed -nE 's/^v([0-9]+)(.([0-9]+)(.([0-9]+))?)?(.*)$$/\1 \3 \5/p')
VER_MAJOR := $(or $(word 1, $(GIT_VERSION)), 0)
VER_MINOR := $(or $(word 2, $(GIT_VERSION)), 0)
VER_PATCH := $(or $(word 3, $(GIT_VERSION)), 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment