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


当前回答

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

git show --pretty=%h 

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

--abbrev=n

其他回答

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

要将任何扩展对象引用转换为哈希,请使用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。

另一个,使用git-log:

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

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

我将如何在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 show --pretty=%h 

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

--abbrev=n