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


当前回答

如果你想要超级黑客的方式:

cat .git/`cat .git/HEAD | cut -d \  -f 2`

基本上,git将HEAD的位置存储在.git/HEAD中,格式为ref:{path from.git}。此命令将读取该位置,将“ref:”切片,并读取它指向的任何文件。

当然,这在分离头模式下会失败,因为head不会是“ref:…”,而是哈希本身-但你知道,我认为你不会期望在bash一行中有那么多聪明。如果你不认为分号是作弊的话。。。

HASH="ref: HEAD"; while [[ $HASH == ref\:* ]]; do HASH="$(cat ".git/$(echo $HASH | cut -d \  -f 2)")"; done; echo $HASH

其他回答

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

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

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

 git reflog

我知道的最简洁的方式是:

git show --pretty=%h 

如果您需要哈希的特定位数,可以添加:

--abbrev=n
git show-ref --head --hash head

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

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

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