How to Rename Git Branches

By | August 21, 2018

You type fast. One more function, one more docstring, one more test. You run ‘make test’. You see all tests green. You are ready to commit, push and finally start the weekend (yes, it’s late Friday afternoon and your colleagues are about to start production deployment). Oh, you suddenly realise that you named the git branch incorrectly! What’s more, you pushed the branch to the remote repository!

For many of us this story sounds familiar. What can we do? In this situation time is crucial. Before any of your colleagues jump on you, you need to fix local and remote branch names. Let’s roll up our sleeves and fix the issue. Here is what we will do:

Rename local branch

Let’s assume we are still on the same branch we want to rename:

$ git branch -m <new-correct-name>

If we are already on a different branch the command looks like this:

$ git branch -m <old-incorrect-name> <new-correct-name>

Delete the old name remote branch and push the new name local branch

$ git push origin :<old-incorrect-name> <new-correct-name>

Reset the upstream branch for the new name local branch

Switch to the branch and after that:

$ git push origin -u <new-correct-name>

Alternatively we can use following 3 steps:

Rename branch locally

$ git branch -m <old-incorrect-branch> <new-correct-branch>

Delete the old branch

$ git push origin :<old-incorrect-branch>

Push the new branch, set local branch to track the new remote

$ git push --set-upstream origin <new-correct-branch>

Off we go! Time for a Friday Pint 😉

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.