如何从命令行获取 main git 分支名称?

How to get main git branch name from command-line?

如何从command-line/terminal获取主分支名称?

我知道默认情况下主分支名为 master,但是可以将其重命名为任何他们想要的名称。

PS—如果能得到本地远程主分支的名字就好了

编辑: 我称之为 main branch 其他人可能称之为 default branchstable branch。这是你(应该)将所有东西(stable/working)合并到其中的那个。

您可能想使用此命令 git branch -r-r 仅用于列出远程分支,如果您想列出这两个用途 -a。 通常 master 分支指向 origin/HEAD 像这样 origin/HEAD -> origin/master

我对git了解不深,但是在git中,通常会有{remote}/HEAD,例如origin/HEAD。这是 man page of git remote 的摘录:

 set-head

    Sets or deletes the default branch (i.e. the target of the
    symbolic-ref refs/remotes/<name>/HEAD) for the named remote.
    Having a default branch for a remote is not required, but allows
    the name of the remote to be specified in lieu of a specific
    branch. For example, if the default branch for origin is set to
    master, then origin may be specified wherever you would normally
    specify origin/master.

据此我了解到 {remote}/HEAD{remote} 的 main/default 分支。可以使用这个获取分支的名称(有人知道 better/plumbing 命令吗?):

git branch -r | grep -Po 'HEAD -> \K.*$'
origin/master

当一个人想要获取本地main/default分支时,通常没有HEAD分支,但是通常只有一个跟踪{remote}/HEAD的分支,我们可以开始使用(同样,肯定有更好的命令):

git branch -vv | grep -Po "^[\s\*]*\K[^\s]*(?=.*$(git branch -rl '*/HEAD' | grep -o '[^ ]\+$'))"
master

当然,如果尚未设置,则需要 set-head,以便在 git remote -r 的输出中有一个 'HEAD/master/main 分支' .因此,在使用上述命令之前,我们需要 运行 下面的命令一次(感谢@pixelbrackets 指出这一点)。

git remote set-head origin -a

更新:

最近,我想了解更多信息(我从here获得的一些命令):

# Get currently checked out local branch name
git rev-parse --abbrev-ref HEAD
# Output: branch

# Get remote branch name that is tracked by currently checked out local branch
git for-each-ref --format='%(upstream:short)' "$(git symbolic-ref -q HEAD)"
# Output: origin/branch

# Get local main branch name
git branch -vv | grep -Po \
  "^[\s\*]*\K[^\s]*(?=.*$(git branch -rl '*/HEAD' | grep -o '[^ ]\+$'))"
# Output: master

# Get remote branch name that is tracked by local main branch (AKA the remote HEAD branch)
git branch -r | grep -Po 'HEAD -> \K.*$'
# Output: origin/master

如果您假设主分支将被称为 mastermain,这是我在本地存储库中快速检测主分支名称的方法:

git_main_branch () {
    git branch | cut -c 3- | grep -E '^master$|^main$'
}

然后我有其他需要知道主分支名称的命令可以使用它。例如,我有 gc-m 代表“git checkout main branch”:

alias gc='git checkout '
alias gc-m='gc $(git_main_branch)'

你也可以这样使用:

alias gc-m='git checkout `git branch -rl "*/HEAD" | rev | cut -d/ -f1 | rev`'