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


当前回答

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

 git reflog

其他回答

git show-ref --head --hash head

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

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

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

要将任何扩展对象引用转换为哈希,请使用git-rev-parse:

git rev-parse HEAD

or

git rev-parse --verify HEAD

要检索短哈希:

git rev-parse --short HEAD

要将引用(例如分支和标记)转换为哈希,请使用git show ref和git for each-ref。

主要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

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

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

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

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

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

要获取完整的SHA:

$ git rev-parse HEAD
cbf1b9a1be984a9f61b79a05f23b19f66d533537

要获取缩短版本:

$ git rev-parse --short HEAD
cbf1b9a