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


当前回答

要获取完整的SHA:

$ git rev-parse HEAD
cbf1b9a1be984a9f61b79a05f23b19f66d533537

要获取缩短版本:

$ git rev-parse --short HEAD
cbf1b9a

其他回答

要获取完整的SHA:

$ git rev-parse HEAD
cbf1b9a1be984a9f61b79a05f23b19f66d533537

要获取缩短版本:

$ git rev-parse --short HEAD
cbf1b9a
git show-ref --head --hash head

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

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

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

我将如何在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 list--max count=1 HEAD

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

git show --pretty=%h 

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

--abbrev=n