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


当前回答

也总是有数字描述。默认情况下,它为您提供--

john@eleanor:/dev/shm/mpd/ncmpc/pkg (master)$ git describe --always
release-0.19-11-g7a68a75

其他回答

git show-ref --head --hash head

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

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

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

为了完整起见,因为还没有人提出过。git/refs/heads/master是一个只包含一行的文件:master上最新提交的哈希。所以你可以从那里读出来。

或者,作为命令:

cat .git/refs/heads/master

更新:

注意,git现在支持将一些head-ref存储在pack-ref文件中,而不是作为/refs/heads/文件夹中的文件。https://www.kernel.org/pub/software/scm/git/docs/git-pack-refs.html

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

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

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

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

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

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

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

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

也总是有数字描述。默认情况下,它为您提供--

john@eleanor:/dev/shm/mpd/ncmpc/pkg (master)$ git describe --always
release-0.19-11-g7a68a75