首页 > 解决方案 > 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 用户对主分支有一个概念,并且根据所有 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 中不存在 - 它只是程序员人脑中的一个概念。


推荐阅读