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


当前回答

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

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

其他回答

以下是Bashshell中使用直接从git文件读取的一行代码:

(head=($(<.git/HEAD)); cat .git/${head[1]})

您需要在git根文件夹中运行上述命令。

当您有存储库文件,但尚未安装git命令时,此方法很有用。

如果不起作用,请检查.git/refs/heads文件夹中您有什么样的头。

我知道的最简洁的方式是:

git show --pretty=%h 

如果您需要哈希的特定位数,可以添加:

--abbrev=n

另一个,使用git-log:

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

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

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

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

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

git show-ref --head --hash head

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

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

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