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


当前回答

在文件“.gitconfig”的主目录中添加以下内容

[alias]
sha = rev-parse HEAD

那么您将有一个更容易记住的命令:

$ git sha
59fbfdbadb43ad0b6154c982c997041e9e53b600

其他回答

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

 git reflog

要获取完整的SHA:

$ git rev-parse HEAD
cbf1b9a1be984a9f61b79a05f23b19f66d533537

要获取缩短版本:

$ git rev-parse --short HEAD
cbf1b9a

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

在文件“.gitconfig”的主目录中添加以下内容

[alias]
sha = rev-parse HEAD

那么您将有一个更容易记住的命令:

$ git sha
59fbfdbadb43ad0b6154c982c997041e9e53b600

以下是Bashshell中使用直接从git文件读取的一行代码:

(head=($(<.git/HEAD)); cat .git/${head[1]})

您需要在git根文件夹中运行上述命令。

当您有存储库文件,但尚未安装git命令时,此方法很有用。

如果不起作用,请检查.git/refs/heads文件夹中您有什么样的头。