gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 14:47:40 26 4
gpt4 key购买 nike

如何从命令行/终端获取主分支名称?

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

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

编辑:我叫什么main branch其他人可能会调用 default branchstable branch .这是您(应该)将所有(稳定/工作) merge 到其中的那个。

最佳答案

我对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} 的主/默认分支.可以使用此获取分支的名称(有人知道更好的/管道命令吗?):
git branch -r | grep -Po 'HEAD -> \K.*$'
origin/master
当想要获取本地主/默认分支时,通常没有 HEAD分支,但是通常只有一个分支跟踪 {remote}/HEAD ,我们可以使用哪个名称(同样,肯定有更好的命令):
git branch -vv | grep -Po "^[\s\*]*\K[^\s]*(?=.*$(git branch -r | grep -Po 'HEAD -> \K.*$'))"
master
当然,一需要 set-head如果还没有设置,为了有一个‘ HEAD/master/main branch' 在 git remote -r 的输出中.因此,在使用上述命令之前,我们需要运行一次以下命令(感谢@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 -r | grep -Po 'HEAD -> \K.*$'))"
# 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

关于git - 如何从命令行获取主 git 分支名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55266918/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com