How to retrieve the hash for the current commit in

2019-01-03 07:09发布

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?

18条回答
仙女界的扛把子
2楼-- · 2019-01-03 07:40

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.

查看更多
霸刀☆藐视天下
3楼-- · 2019-01-03 07:42

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

john@eleanor:/dev/shm/mpd/ncmpc/pkg (master)$ git describe --always
release-0.19-11-g7a68a75
查看更多
一夜七次
4楼-- · 2019-01-03 07:45

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

查看更多
乱世女痞
5楼-- · 2019-01-03 07:46

Commit hash

git show -s --format=%H

Abbreviated commit hash

git show -s --format=%h

Click here for more git show examples.

查看更多
Root(大扎)
6楼-- · 2019-01-03 07:46

The most succinct way I know:

git show --pretty=%h 

If you want a specific number of digits of the hash you can add:

--abbrev=n
查看更多
一纸荒年 Trace。
7楼-- · 2019-01-03 07:48

Here is another direct-access implementation:

head="$(cat ".git/HEAD")"
while [ "$head" != "${head#ref: }" ]; do
  head="$(cat ".git/${head#ref: }")"
done

This also works over http which is useful for local package archives (I know: for public web sites it's not recommended to make the .git directory accessable):

head="$(curl -s "$baseurl/.git/HEAD")"
while [ "$head" != "${head#ref: }" ]; do
  head="$(curl -s "$baseurl/.git/${head#ref: }")"
done
查看更多
登录 后发表回答