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


当前回答

以下是另一种方法:)

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

其他回答

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

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

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

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

commit d25c95d88a5e8b7e15ba6c925a1631a5357095db .. (info about your head)

d25c95d88a5e8b7e15ba6c925a1631a5357095db, is your SHA for last commit.

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

 git reflog