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

Viewed 60142

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?

6 Answers

Consolidating some of the answers:

git tag --contains [<ref>]

and

git tag --points-at [<ref>]

or just

git tag

behave the same, printing any (and all) tags for the specified ref or the current commit if not specified.

git describe --tags [<ref>]

where <ref> defaults to the current commit, exits with 128 if no tags are associated with the commit, and prints a tag associated with the commit (there does not seem to be a pattern).

git describe [<ref>] behaves the same as with --tags except that it only prints annotated tags.

Supplying the option --contains to describe will print the a tag which is associated with an ancestor of the specified commit. For example

$ git init
Initialized empty Git repository in /tmp/test
$ git commit -m one --allow-empty
[master (root-commit) 7fdfff2] one
$ git commit -m two --allow-empty
[master cd5f8f1] two
$ git tag -am foo foo
$ git tag bar
$ git log --format=oneline
cd5f8f1f4f29eb164f83e224768ccaf37fe170ed (HEAD -> master, tag: foo, tag: bar) two
7fdfff2ce5e3347f8eee4c9f2413dbd4e90060e1 one
$ git describe 7fdfff2ce5e3347f8eee4c9f2413dbd4e90060e1
fatal: No tags can describe '7fdfff2ce5e3347f8eee4c9f2413dbd4e90060e1'.
Try --always, or create some tags.
$ git describe --contains 7fdfff2ce5e3347f8eee4c9f2413dbd4e90060e1
bar~1

Related