如何用最短命令从远程检出新分支并指定不同上游?
简化从主仓库创建新分支并设置上游的方法
首先,你想要的一步到位创建分支并关联上游的需求,可以通过简洁的命令组合实现,Git本身没有单条原生命令直接完成,但两行(或一行组合)已经足够简便:
方法一:用 git checkout(兼容旧版本Git)
先从the-project/master创建并切换到new-feature分支,再推送到origin并设置上游:
git checkout -B new-feature the-project/master git push -u origin new-feature
或者合并成一行执行:
git checkout -B new-feature the-project/master && git push -u origin new-feature
方法二:用 git switch(Git 2.23+ 推荐的现代命令)
git switch是Git官方推荐替代git checkout分支切换功能的命令,语法更清晰直观:
git switch -c new-feature the-project/master git push -u origin new-feature
同样可以合并为一行:
git switch -c new-feature the-project/master && git push -u origin new-feature
关于你提到的命令的说明
你尝试的git checkout the-project/master -B new-feature --set-upstream-to origin无法生效,原因有两点:
--set-upstream-to需要指定完整的远程分支路径(比如origin/new-feature),而不是远程仓库名origin;- 在你把本地分支推送到
origin之前,origin/new-feature这个远程分支还不存在,直接设置上游会报错。
而--no-auto-upstream这个选项其实是多余的:
Git默认情况下,从远程跟踪分支(比如the-project/master)创建新本地分支时,不会自动设置上游关联——只有当你直接从远程分支(比如origin/master)检出本地分支时,才会自动关联上游。所以你直接用git checkout -B new-feature the-project/master创建的分支,本身就没有自动设置上游,不需要额外参数禁用。
内容的提问来源于stack exchange,提问作者Luciano
相关产品推荐
相关产品推荐

