我有一个 bash 脚本,它接受分支名称(例如“master”或“feature/foo”)或提交哈希(例如“1234abcd”)的字符串。
我已签出存储库,因此我可以调用 git。
确定字符串是分支名称还是提交哈希的最佳方法是什么?
#!/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
来解决它。
例子:
$ 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 提示(旧提交) https://github.com/git-tips/tips/tree/39d1012fc9652aa9853d58d0fd1086070d82e4f7#check-if-the-change-was-a-part-of-a-release
更新:正如@kporter提到的,还有--name-only
标志(截至 2020 年 4 月 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 https://git-scm.com/docs/git-name-rev
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)