How to find the tag associated with a given git commit?

For releases I usually tag with something like v1.1.0. During my build script I am creating a fwVersion.c file that contains the current git info. Currently, I have commit, and branch info in the file, but I would like to add the tag.

Is this possible?


Check the documentation for git describe. It finds the nearest tag to a given commit (that is a tag which points to an ancestor of the commit) and describes that commit in terms of the tag.

If you only want to know if the commit is pointed to by a tag then you can check the output of:

git describe --exact-match <commit-id>

If what you want is the first tag containing the commit then:

git describe --contains <commit>

gives the best answer IMO. If you have frequent tags than using "git tag --contains" on an old commit in a big repository can take a while to run and gives you all of the tags that contain that commit.

This form of git describe runs very quickly and gives you a single output value which is the first tag containing the commit and how far back your commit is.


How about this?

git tag --points-at <commit-id>

It gives you all the tags the given commit has (whereas git describe only gives you one), and does not include tags on descendant commits (like git tag --contains does).


You can find this information in the manual

git tag --contains <commit>

I found the combo of both top answers to give me what i wanted like so:

git describe --tags --exact-match <commit-id>

This gives you the tag that is ONLY for that commit and for ones without annotation. Useful when you want to find tags and not worry about stripping the formatting off then (for Jenkins for example).

eg. $ git describe --tags --exact-match head~2

Gives you:

$ ReleaseBeta