Home > Software design >  Get latest commit sha or tag with git
Get latest commit sha or tag with git

Time:10-13

How do I use git to get either the tag of the current commit or, if the tag is not present, the short commit sha?

I have been using git describe --always, but it's not working anymore for some reason, it's now returning this last tag weeks old with some random numbers and some sha.

❯ git describe --always
some-tag-1437-g9d3616e339
❯ git log
9d3616e339 [11 minutes ago] (HEAD -> master, origin/master, origin/HEAD) message
# ... bunch of other commits with no tags
81bbfc64e2 [8 weeks ago] (tag: some-tag) message

CodePudding user response:

If you want to have the list of tags that point at the current commit, use git tag --points-at :

git tag --points-at HEAD
git tag --points-at HEAD "v-*"  # only keep tags starting with 'v-'

If you want to have either a tag name or a commit hash, you can add a little scripting :

# in case there would be several tags: take the first one
name=$(git tag --points-at HEAD "v-*" | head -1)
# if no tag: get the short sha
if [ -z "$name" ]; then
   name=$(git rev-parse --short HEAD)
fi

# do something with $name ...
echo $name
  •  Tags:  
  • git
  • Related