Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the commit hash for a tag

Tags:

git

It is related to Making git show to show information in a machine parseable format but I am getting tired of the fact that I now have to do a lot of parsing to get the commit hash.

Can someone give me a command that will print the commit hash (and only the commit hash) tag for a given git tag? I was hoping

git show mylabel --pretty=format:"%H" --quiet 

Would just print me my commit # but it says

tag mylabel
Tagger: user <[email protected]>

Some comment

446a52cb4aff90d0626b8232aba8c40235c16245

I was expecting one line of output with just the commit line but I now have to parse for the last line?

like image 400
Kannan Ekanath Avatar asked May 29 '13 15:05

Kannan Ekanath


2 Answers

What about git log -1 --format=format:"%H" mylabel

EDIT:

Actually a better solution would be :

git show-ref -s mylabel

WARNING This only works for Unannotated tags For a more general and safer command see https://stackoverflow.com/a/1862542/1586965

EDIT bis: As mentioned in the comments, be careful with annotated commits (which are objects of their own). To have a more generic solution, read @michas answer.

You can see the difference when you do a git show-ref -d mylabel.


Resources:

  • git show-ref
like image 51
Colin Hebert Avatar answered Sep 30 '22 14:09

Colin Hebert


git help rev-parse says:

   <rev>^{}, e.g. v0.99.8^{}
       A suffix ^ followed by an empty brace pair means the object could be a tag, and dereference the tag recursively until a non-tag object is found.

Generally you use tag^{} to refer to that commit.

You have two different kind of tags:

  • lightweight tags are just pointers to an existing commit
  • annotated tags are objects on there own which contain a pointer to a separate commit object

Use git rev-parse tag to get the SHA1 of the tag itself.

Use git rev-parse tag^{} to get the SHA1 of the underlaying commit.

For lightweight tags both are the same. For annotated tags they are not.

You can also use git show-ref -d tag, which will show you both the SHA1 of the tag and the SHA1 of the associated commit.

There is also git show tag to give you details about an (annotated) tag.

like image 29
michas Avatar answered Sep 30 '22 15:09

michas