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


当前回答

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

git show --pretty=%h 

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

--abbrev=n

其他回答

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

git show --pretty=%h 

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

--abbrev=n

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

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

commit d25c95d88a5e8b7e15ba6c925a1631a5357095db .. (info about your head)

d25c95d88a5e8b7e15ba6c925a1631a5357095db, is your SHA for last commit.

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

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

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

在文件“.gitconfig”的主目录中添加以下内容

[alias]
sha = rev-parse HEAD

那么您将有一个更容易记住的命令:

$ git sha
59fbfdbadb43ad0b6154c982c997041e9e53b600

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

last_commit=$(git rev-parse HEAD);

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

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