乐闻世界logo
搜索文章和话题

How do i rename both a git local and remote branch name?

8 个月前提问
4 个月前修改
浏览次数159

5个答案

1
2
3
4
5

如果错误地命名了分支并将其推送到远程存储库,请按照以下步骤重命名该分支

  1. 重命名您的本地分支:

    • 如果在要重命名的分支上:
    • bash
      git branch -m new-name
    • 如果在不同的分支:
    • bash
      git branch -m old-name new-name
  2. 删除 old-name远程分支并推送 new-name本地分支git push origin :old-name new-name

  3. 重置新名称本地分支的上游分支: 切换到该分支,然后: git push origin -u new-name

2024年6月29日 12:07 回复

示意图,可爱的 git 远程图


有几种方法可以实现这一点:

  1. 更改您的本地分支,然后推送您的更改
  2. 使用新名称将分支推送到远程,同时在本地保留原始名称

重命名本地和远程

shell
# Rename the local branch to the new name git branch -m <old_name> <new_name> # Delete the old branch on remote - where <remote> is, for example, origin git push <remote> --delete <old_name> # Or shorter way to delete remote branch [:] git push <remote> :<old_name> # Prevent git from using the old name when pushing in the next step. # Otherwise, git will use the old upstream name instead of <new_name>. git branch --unset-upstream <new_name> # Push the new branch to remote git push <remote> <new_name> # Reset the upstream branch for the new_name local branch git push <remote> -u <new_name>

控制台截图


仅重命名远程分支

信用:ptim

shell
# In this option, we will push the branch to the remote with the new name # While keeping the local name as is git push <remote> <remote>/<old_name>:refs/heads/<new_name> :<old_name>

重要的提示:

当您使用git branch -m(移动)时,Git 也会使用新名称更新您的跟踪分支。

git remote rename legacy legacy

git remote rename正在尝试更新配置文件中的远程部分。它将使用给定名称的遥控器重命名为新名称,但在您的情况下,它没有找到任何名称,因此重命名失败。

它不会按照你的想法去做;它将重命名您的本地配置远程名称而不是远程分支。 


注意 Git 服务器可能允许您使用 Web 界面或外部程序(如 Sourcetree 等)重命名 Git 分支,但您必须记住,在 Git 中所有工作都是在本地完成的,因此建议使用上述命令去工作。

2024年6月29日 12:07 回复

查询正在使用的分支

shell
git branch -a

切换到要重命名的分支

bash
git checkout branch_to_rename

使用重命名分支

bash
git branch -m new_name

推动更改

bash
git push origin :old_name new_name
2024年6月29日 12:07 回复
  • 重命名您的本地分支机构

如果您在要重命名的分支上:

shell
git branch -m new-name

如果您当前住在不同的分支机构:

shell
git branch -m old-name new-name
  • 删除旧名称的远程分支并推送新名称的本地分支。

留在目标分支上并且:

shell
git push origin :old-name new-name
  • 重置新名称本地分支的上游分支。

切换到目标分支然后:

shell
git push origin -u new-name
2024年6月29日 12:07 回复

看来有一个直接的办法:

如果您真的只想远程重命名分支(而不同时重命名任何本地分支),您可以使用单个命令来完成此操作,例如

git push <remote> <remote>/<old_name>:refs/heads/<new_name> :<old_name>

在 Git 中远程重命名分支

有关更多详细信息,请参阅原始答案。

2024年6月29日 12:07 回复

你的答案