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


当前回答

提交哈希

git show -s --format=%H

缩写的提交哈希

git show -s --format=%h

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

单击此处查看更多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文件夹中您有什么样的头。

我将如何在python中实现(基于@kenorb的bash答案)

def get_git_sha():
    # Which branch are we on?
    branch = open(".git/HEAD", "r").read()

    # Parse output "ref: refs/heads/my_branch" -> my_branch
    branch = branch.strip().split("/")[-1]

    # What's the latest commit in this branch?
    return open(f".git/refs/heads/{branch}").read().strip()

要将任何扩展对象引用转换为哈希,请使用git-rev-parse:

git rev-parse HEAD

or

git rev-parse --verify HEAD

要检索短哈希:

git rev-parse --short HEAD

要将引用(例如分支和标记)转换为哈希,请使用git show ref和git for each-ref。

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

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

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