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


当前回答

以下是另一种方法:)

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

其他回答

要获取完整的SHA:

$ git rev-parse HEAD
cbf1b9a1be984a9f61b79a05f23b19f66d533537

要获取缩短版本:

$ git rev-parse --short HEAD
cbf1b9a

主要git repo和子模块的漂亮打印:

echo "Main GIT repo:"
echo $(git show -s --format=%H) '(main)'
echo "Sub-modules:"
git submodule status | awk '{print $1,$2}'

示例输出:

3a032b0992d7786b00a8822bbcbf192326160cf9 (main)
7de695d58f427c0887b094271ba1ae77a439084f sub-module-1
58f427c0887b01ba1ae77a439084947de695d27f sub-module-2
d58f427c0887de6957b09439084f4271ba1ae77a sub-module-3

我将如何在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-rev-parse-HEAD完成了这个任务。

如果您需要在保存实际分行(如果有的话)之前将其存储到结账台:

cat .git/HEAD

示例输出:

ref: refs/heads/master

解析它:

cat .git/HEAD | sed "s/^.\+ \(.\+\)$/\1/g"

如果您有Windows,则可以考虑使用wsl.exe:

wsl cat .git/HEAD | wsl sed "s/^.\+ \(.\+\)$/\1/g"

输出:

refs/heads/master

该值可能稍后用于git签出,但它会指向其SHA。要使其通过名称指向实际的当前分支,请执行以下操作:

wsl cat .git/HEAD | wsl sed "s/^.\+ \(.\+\)$/\1/g" | wsl sed "s/^refs\///g"  | wsl sed "s/^heads\///g"

输出:

master

使用git rev list--max count=1 HEAD