如何获取Git中当前提交的哈希?
当前回答
在gitbash上,只需运行$git日志-1
您将看到,这些行遵循您的命令。
commit d25c95d88a5e8b7e15ba6c925a1631a5357095db .. (info about your head)
d25c95d88a5e8b7e15ba6c925a1631a5357095db, is your SHA for last commit.
其他回答
下面是另一个直接访问实现:
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
git show-ref --head --hash head
如果你追求速度,Deestan提到的方法
cat .git/refs/heads/<branch-name>
比这里列出的任何其他方法都快得多。
要获取缩短的提交哈希,请使用%h格式说明符:
git log --pretty=format:'%h' -n 1
%H表示长提交哈希。此外,可以直接使用-1代替-n 1。
我将如何在python中实现(基于@kenorb的bash答案)
def get_git_sha():
# Which branch are we on?
branch = open(".git/HEAD", "r").read()
# Parse output "ref: refs/heads/my_branch" -> my_branch
branch = branch.strip().split("/")[-1]
# What's the latest commit in this branch?
return open(f".git/refs/heads/{branch}").read().strip()
如果你想要超级黑客的方式:
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添加?
- Rubymine:如何让Git忽略Rubymine创建的.idea文件
- Gitignore二进制文件,没有扩展名
- Git隐藏错误:Git隐藏弹出并最终与合并冲突
- 了解Git和GitHub的基础知识
- 没有。Git目录的Git克隆
- Git与Mercurial仓库的互操作性
- 忽略git中修改(但未提交)的文件?
- “git restore”命令是什么?“git restore”和“git reset”之间有什么区别?
- Git合并与强制覆盖
- Git拉另一个分支
- 在Bash命令提示符上添加git分支
- 如何更改Git日志日期格式
- git pull -rebase和git pull -ff-only之间的区别