如何获取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

其他回答

提交哈希

git show -s --format=%H

缩写的提交哈希

git show -s --format=%h

-s标志与--no补丁相同,代表“抑制差异输出”。

单击此处查看更多git显示示例。

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

echo“正在打印当前分支的上次提交id#:”;

 git reflog

在gitbash上,只需运行$git日志-1

您将看到,这些行遵循您的命令。

commit d25c95d88a5e8b7e15ba6c925a1631a5357095db .. (info about your head)

d25c95d88a5e8b7e15ba6c925a1631a5357095db, is your SHA for last commit.

为了完整起见,因为还没有人提出过。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