How to rename a branch you already pushed to remote?

How to rename a branch? #dev #git #workflow #coding

How to rename a branch you already pushed to remote?
Photo by Pakata Goh / Unsplash

Let's say you start working on a task and create a branch with the same name. But as you progress further, you realise that the work itself doesn't describe the task name or the nature of work changes in between. However, you have already pushed your changes on remote.

How do you rename the branch both locally and remotely?

  1. git checkout <old_name>
  2. git branch -m <new_name>
  3. git push origin -u <new_name>
  4. git push origin --delete <old_name>

Voila.

There are also different ways of achieving the same outcome. For example, this gist does it in fewer lines.

git branch -m old_branch new_branch         # Rename branch locally    
git push origin :old_branch                 # Delete the old branch    
git push --set-upstream origin new_branch   # Push the new branch, set local branch to track the new remote
gist

You can also use GUI tools to achieve the same outcome in few clicks.


References:

https://linuxize.com/post/how-to-rename-local-and-remote-git-branch/

rename git branch locally and remotely
rename git branch locally and remotely. GitHub Gist: instantly share code, notes, and snippets.