Skip to content

Instantly share code, notes, and snippets.

@Trogious
Last active April 23, 2020 11:59
Show Gist options
  • Save Trogious/861518aec8c7deab95a7a6f7ab663b83 to your computer and use it in GitHub Desktop.
Save Trogious/861518aec8c7deab95a7a6f7ab663b83 to your computer and use it in GitHub Desktop.
How to get latest git tag or commit ID (shell)

How to get latest git tag or commit ID (shell)

The following will give you the latest git tag name (if the HEAD is tagged) or latest commit ID otherwise. After execution the X_VERSION variable holds the end value.

Why is this useful?

I use it to name packages of my builds and other versioning purposes. See example here.

The script:

X_GIT_COMMITID=`git rev-parse --short HEAD | tr -d "\n" | sed 's/ //g'`
X_GIT_TAG=`git tag --points-at $X_GIT_COMMITID | tr -d "\n" | sed 's/ //g'`
if [ -n "$X_GIT_TAG" ]; then
  X_VERSION="$X_GIT_TAG"
else
  X_VERSION="git-$X_GIT_COMMITID"
fi
echo $X_VERSION
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment