Skip to content

Instantly share code, notes, and snippets.

@bitmvr
Last active May 24, 2024 08:29
Show Gist options
  • Save bitmvr/9ed42e1cc2aac799b123de9fdc59b016 to your computer and use it in GitHub Desktop.
Save bitmvr/9ed42e1cc2aac799b123de9fdc59b016 to your computer and use it in GitHub Desktop.
A POSIX Compliant SemVer Parser in Pure Bash
#!/usr/bin/env bash
VERSION="${1#[vV]}"
VERSION_MAJOR="${VERSION%%.*}"
VERSION_MINOR_PATCH="${VERSION#*.}"
VERSION_MINOR="${VERSION_MINOR_PATCH%%.*}"
VERSION_PATCH_PRE_RELEASE="${VERSION_MINOR_PATCH#*.}"
VERSION_PATCH="${VERSION_PATCH_PRE_RELEASE%%[-+]*}"
VERSION_PRE_RELEASE=""
case "$VERSION" in
*-*)
VERSION_PRE_RELEASE="${VERSION#*-}"
VERSION_PRE_RELEASE="${VERSION_PRE_RELEASE%%+*}"
;;
esac
echo "Version: ${VERSION}"
echo "Version [major]: ${VERSION_MAJOR}"
echo "Version [minor]: ${VERSION_MINOR}"
echo "Version [patch]: ${VERSION_PATCH}"
echo "Version [pre-release]: ${VERSION_PRE_RELEASE}"
@andyfeller
Copy link

chefs kiss

@mman
Copy link

mman commented May 20, 2024

Just a note that this does not correctly parse out minor version out of 2.0.0-rc.2

€ ./exmple--parse-semver-with-bash.sh 2.0.0-rc.2   
Version: 2.0.0-rc.2
Version [major]: 2
Version [minor]: 0.0-rc
Version [patch]: 2

https://semver.org/spec/v2.0.0-rc.2.html

@bitmvr
Copy link
Author

bitmvr commented May 23, 2024

@mman : Nice catch. When I built this for a small project, I never used pre-releases. I've updated the logic to account for per-releases as well as remove any potential metadata that could exist.

@andyfeller : If you're still using this logic anywhere, you may want to update it ;)

@bitmvr
Copy link
Author

bitmvr commented May 23, 2024

Well, actually there is still one bug in the logic. The last test I ran locally, the rc is still a part of the patch release. I need to account for that.

bitmvr@bitmvr-macbook-00 tmp % ./version-parse.sh 1.2.3-rc-4.5.6 
Version: 1.2.3-rc-4.5.6
Version [major]: 1
Version [minor]: 2
Version [patch]: 3-rc
Version [pre-release]: rc-4.5.6

@bitmvr
Copy link
Author

bitmvr commented May 23, 2024

Okay, I've patched it. I will add comments later around what's happening where as parameter expansion in Bash can be confusing.

@mman
Copy link

mman commented May 24, 2024

@bitmvr Cool thanks a lot, I think that as much as SemVer is popular, we actually (if I am not mistaken) miss generally well available installed everywhere typ of tool to actually parse semver, to use in GitHub actions, and build scripts, etc. so your script is actually very handy :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment