如何获取Git中当前提交的哈希?


当前回答

使用git rev list--max count=1 HEAD

其他回答

下面是另一个直接访问实现:

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

这也适用于http,这对本地包存档很有用(我知道:对于公共网站,不建议将.git目录设置为可访问):

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

在文件“.gitconfig”的主目录中添加以下内容

[alias]
sha = rev-parse HEAD

那么您将有一个更容易记住的命令:

$ git sha
59fbfdbadb43ad0b6154c982c997041e9e53b600

另一个,使用git-log:

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

它与“outofculture”非常相似,不过稍短一些。

git show-ref --head --hash head

如果你追求速度,Deestan提到的方法

cat .git/refs/heads/<branch-name>

比这里列出的任何其他方法都快得多。

要获取缩短的提交哈希,请使用%h格式说明符:

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

%H表示长提交哈希。此外,可以直接使用-1代替-n 1。