git - Command to get the name of git's default branch
问题描述
For scripting purposes I need to know the name of the "master" branch. I have some projects with the deprecated, old naming "master. I have other projects where the branch is named "main".
I would like to determine that name programatically. How do I find that name with a command?
我经常使用的一个示例是删除 arez 已经合并到 master ( git branch --merged master | grep -v master |xargs git branch -d
) 的本地分支。在这种情况下,我需要提供“main”或“master”作为值。
解决方案
Git 没有主分支的概念。因此,您想要做的事情实际上是不可能的。
Git 用户对主分支有一个概念,并且根据所有 git 用户的普遍共识(以及最初由 Linus Torvalds 给出的一般建议),这个分支通常称为master,但并非必须如此。
主分支之所以可以命名为master以外的名称,是因为git 没有主分支的概念。
其他人创建的软件,例如 Github、Bitbucket 或 Gitlab,确实有主分支的概念。如果这是您所要求的,您将需要使用这些软件公开的 API 来找出哪个分支是主分支。当然,您需要知道开发人员正在使用什么服务才能使用其 API。
例如对于 Github,您可以这样做来获取主分支:
curl -H "Accept: application/vnd.github.v3+json" \
https://api.github.com/repos/slebetman/httpstress |
grep default_branch
然而,单独使用 git 不可能做你想做的事,因为主分支的概念在 git 中不存在 - 它只是程序员人脑中的一个概念。
推荐阅读
- python - seq2seq模型中有多个输入时该怎么办?
- java - 在 Main 方法中实例化类时不是语句错误
- html - 响应式媒体卡图像在左侧,文本在右侧
- angular - 无法显示来自 Contentful (Angular) 的参考(许多)内容类型的标题
- javascript - 选择购物车内的物品并升级购物车的持有柜台
- excel - 使用 VBA 可以设置工作表以适应一页并用完整个页面
- c++ - 我可以询问并存储可以是数字或字符的输入并在条件表达式中使用它吗?
- paypal - 使用 PayPal 捐赠按钮预先检查定期选项
- xslt - 使用 xslt 将 xml 数据从 1 个标签转换为 2 个不同的列
- python - 调用 C 例程的调试器 python 代码