Advertisement
Advertisement


How to retrieve the hash for the current commit in Git?


Question

I would like to retain (for now) the ability to link Git changesets to workitems stored in TFS.

I already wrote a tool (using a hook from Git) in which I can inject workitemidentifiers into the message of a Git changeset.

However, I would also like to store the identifier of the Git commit (the hash) into a custom TFS workitem field. This way I can examine a workitem in TFS and see what Git changesets are associated with the workitem.

How can I easily retrieve the hash from the current commit from Git?

2017/10/23
1
1996
10/23/2017 6:57:31 PM

Accepted Answer

To turn arbitrary extended object reference into SHA-1, use simply git-rev-parse, for example

git rev-parse HEAD

or

git rev-parse --verify HEAD

You can also retrieve the short version like this

git rev-parse --short HEAD

Sidenote: If you want to turn references (branches and tags) into SHA-1, there is git show-ref and git for-each-ref.

2020/07/21
2913
7/21/2020 5:22:43 PM

If you only want the shortened hash:

git log --pretty=format:'%h' -n 1

Further, using %H is another way to get the long hash.

2011/09/30

Another one, using git log:

git log -1 --format="%H"

It's very similar to the of @outofculture though a bit shorter.

2011/11/21

To get the full SHA:

$ git rev-parse HEAD
cbf1b9a1be984a9f61b79a05f23b19f66d533537

To get the shortened version:

$ git rev-parse --short HEAD
cbf1b9a
2016/07/29

For completeness, since no-one has suggested it yet. .git/refs/heads/master is a file that contains only one line: the hash of the latest commit on master. So you could just read it from there.

Or, as as command:

cat .git/refs/heads/master

Update:

Note that git now supports storing some head refs in the pack-ref file instead of as a file in the /refs/heads/ folder. https://www.kernel.org/pub/software/scm/git/docs/git-pack-refs.html

2013/09/11

There's always git describe as well. By default it gives you --

[email protected]:/dev/shm/mpd/ncmpc/pkg (master)$ git describe --always
release-0.19-11-g7a68a75
2018/12/14

Source: https://stackoverflow.com/questions/949314
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]