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


当前回答

我需要一些更不同的东西:显示提交的完整sha1,但如果工作目录不干净,则在末尾添加星号。除非我想使用多个命令,否则前面答案中的选项都不起作用。

这是一个可以:git-descripte--always--abbrev=0--match“NOT A TAG”--dirty=“*”结果:f5366ccb21588c0d7a5f7d9fa1d3f85e9f9d1ffe*

说明:描述(使用带注释的标记)当前提交,但仅使用包含“NOT A TAG”的标记。由于标记不能有空格,因此这永远不会与标记匹配,并且因为我们希望显示一个结果——始终,命令会返回显示提交的完整(--abbrev=0)sha1,如果工作目录是--dirty,则会附加一个星号。

如果您不想附加星号,这与前面回答中的所有其他命令一样:git-descripte--always--abbrev=0--match“NOT A TAG”结果:f5366ccb21588c0d7a5f7d9fa1d3f85e9f9d1ffe

其他回答

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

下面是另一个直接访问实现:

head="$(cat ".git/HEAD")"
while [ "$head" != "${head#ref: }" ]; do
  head="$(cat ".git/${head#ref: }")"
done

这也适用于http,这对本地包存档很有用(我知道:对于公共网站,不建议将.git目录设置为可访问):

head="$(curl -s "$baseurl/.git/HEAD")"
while [ "$head" != "${head#ref: }" ]; do
  head="$(curl -s "$baseurl/.git/${head#ref: }")"
done

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

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

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

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

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

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

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

commit d25c95d88a5e8b7e15ba6c925a1631a5357095db .. (info about your head)

d25c95d88a5e8b7e15ba6c925a1631a5357095db, is your SHA for last commit.

也许你想要一个别名,这样你就不必记住所有漂亮的细节。完成以下步骤之一后,您将能够简单地键入:

$ git lastcommit
49c03fc679ab11534e1b4b35687b1225c365c630

根据公认的答案,有两种设置方法:

1) 通过编辑全局配置(我最初的答案),教git明确的方法:

 # open the git config editor
 $ git config --global --edit
 # in the alias section, add
 ...
 [alias]
   lastcommit = rev-parse HEAD
 ...

2) 或者如果你喜欢一个快捷方式来教git一个快捷方法,正如Adrien最近评论的那样:

$ git config --global alias.lastcommit "rev-parse HEAD"

从这里开始,使用gitlastcommit显示最后一次提交的哈希。