如何从提交哈希中分辨出git分支名称? [英] How to tell git branch name from commit hash?
问题描述
我有一个bash脚本,它接受分支名称(例如"master"或"feature/foo")或提交哈希(例如"1234abcd")的字符串.
I have a bash script which accepts a string of either a branch name (e.g., "master", or "feature/foo") or a commit hash (e.g. "1234abcd").
我已经检出了存储库,所以我可以叫git.
I have the repository checked out, so I can call git.
确定字符串是分支名称还是提交哈希的最佳方法是什么?
What is the best way to determine whether the string is a branch name or a commit hash?
#!/bin/bash
commit_or_branch="$1"
cd /path/to/my_repo
git fetch
if <is_branch $commit_or_branch>
then
echo "it's a branch"
else
echo "it's a commit"
fi
推荐答案
如果您希望使用一种可靠的机制来告诉相对名称(例如,SHA1可能是一个在命名分支后面的提交),则可以使用git name-rev
解决它.
If you would like a robust mechanism to tell relative names (e.g. you SHA1 is possibly one or so commits behind a named branch), you can use git name-rev
to resolve it.
示例:
$ git config remote.upstream.url
https://github.com/RobotLocomotion/drake.git
$ git log --oneline -n 5
7530a95 Merge pull request #5743 from soonho-tri/pr-reformat-mathematical_program
ebc8f25 Suppresses console output of speed_bump.obj genrule. (#5726)
d8b9a0b Merge pull request #5735 from david-german-tri/namespaces
79e10e8 Remove redundant 'symbolic::' prefix from mathematical_program code
b68b590 Clean up mathematical_program code by adding using std::*
$ git name-rev HEAD
HEAD master
$ git name-rev 79e10e8
79e10e8 master^2
$ git name-rev HEAD~20
HEAD~20 remotes/origin/issue/5646_return_binding~3
参考: Git提示(旧提交)
更新:如@kporter所述,还有--name-only
标志(自2020/04/21起具有新提交):
UPDATE: As @kporter mentioned, there is also the --name-only
flag (with new commits as of 2020/04/21):
$ git name-rev HEAD
HEAD tags/last_sha_with_original_matlab~313
$ git name-rev --name-only HEAD~20
tags/last_sha_with_original_matlab~333
命令行参考: git name-rev
Command-Line Reference: git name-rev
这篇关于如何从提交哈希中分辨出git分支名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!