在本地和远程重命名 Git 分支?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36999937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 04:08:48  来源:igfitidea点击:

Rename a Git branch locally and remotely?

gitgit-branch

提问by Rémi Becheras

Is there a way to rename a Git branch locally and push it to the remote branch, even if there are already many commits pushed to the remote branch?

有没有办法在本地重命名 Git 分支并将其推送到远程分支,即使已经有很多提交推送到远程分支?

Or, is it necessary to create a new local branch, delete the old local branch, and then repeat the operation on the remote repository?

或者,是否需要创建一个新的本地分支,删除旧的本地分支,然后在远程存储库上重复该操作?

回答by Rémi Becheras

Yes,

是的,

the feature moveexists to rename the branch locally

该功能move存在以在本地重命名分支

git branch --move <old_name> <new_name>

but to push it, you must delete the old and push the new

但是要推送它,您必须删除旧的并推送新的

git checkout <new_name>
git push origin [--set-upstream] <new_name>
git push origin --delete <old_name>

--set-upstreamis optional, it configure the new local branch to track the pushed one

--set-upstream是可选的,它配置新的本地分支来跟踪推送的

You can use the following shorthands:

您可以使用以下简写:

  • move locally (--move) :

    git branch -m <old_name> <new_name>
    
  • push new branch (--set-upstream, optional) :

    git push origin [-u] <new_name>
    
  • delete (--delete) :

    git push origin -d <old_name>
    
  • 本地移动(--move):

    git branch -m <old_name> <new_name>
    
  • 推送新分支(--set-upstream,可选):

    git push origin [-u] <new_name>
    
  • 删除 (--delete) :

    git push origin -d <old_name>
    

NB.

注意。

Thanks to torek's comment:

感谢 torek 的评论:

Worth mentioning, by the way, is that you should

顺便说一句,值得一提的是,你应该

  1. notify other users who share the upstream that you will be doing this, and
  2. do this in the order shown (set new name, then delete old).
  1. 通知共享上游的其他用户您将执行此操作,并且
  2. 按照显示的顺序执行此操作(设置新名称,然后删除旧名称)。

The reason for #1 is that those users will need to adjust.

#1 的原因是这些用户需要调整。

The reason for #2 is mainly just efficiency: it avoids having to re-copy objects to an upstream repo that drops commits on branch deletion (most bare repositories do that, and most repositories that accept pushes are bare)

#2 的原因主要是效率:它避免了必须将对象重新复制到上游存储库,该存储库在分支删除时删除提交(大多数裸存储库都这样做,而大多数接受推送的存储库都是裸存储库)