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


当前回答

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

git show --pretty=%h 

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

--abbrev=n

其他回答

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

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

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

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

要获取缩短的提交哈希,请使用%h格式说明符:

git log --pretty=format:'%h' -n 1

%H表示长提交哈希。此外,可以直接使用-1代替-n 1。

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

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

commit d25c95d88a5e8b7e15ba6c925a1631a5357095db .. (info about your head)

d25c95d88a5e8b7e15ba6c925a1631a5357095db, is your SHA for last commit.

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

last_commit=$(git rev-parse HEAD);

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

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