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


当前回答

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

last_commit=$(git rev-parse HEAD);

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

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

其他回答

以下是另一种方法:)

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

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

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

要获取完整的SHA:

$ git rev-parse HEAD
cbf1b9a1be984a9f61b79a05f23b19f66d533537

要获取缩短版本:

$ git rev-parse --short HEAD
cbf1b9a

另一个,使用git-log:

git log -1 --format="%H"

它与“outofculture”非常相似,不过稍短一些。

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

git show --pretty=%h 

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

--abbrev=n