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


当前回答

我将如何在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()

其他回答

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

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

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

以下是另一种方法:)

git log | grep -o '\w\{8,\}' | head -n 1

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

git show --pretty=%h 

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

--abbrev=n

另一个,使用git-log:

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

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

如果需要在脚本期间将哈希存储在变量中,可以使用

last_commit=$(git rev-parse HEAD);

或者,如果您只需要前10个字符(如github.com)

last_commit=$(git rev-parse --short=10 HEAD);