如何获取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()

其他回答

git show-ref --head --hash head

如果你追求速度,Deestan提到的方法

cat .git/refs/heads/<branch-name>

比这里列出的任何其他方法都快得多。

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

last_commit=$(git rev-parse HEAD);

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

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

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

 git reflog

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

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

$ 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显示最后一次提交的哈希。