Renaming A Branch Both Locally And Remotely

Git branches are a great way to test and work on new features. Teams often have a naming convention for their branches as well; if you are using the popular project management app Trello you might use the card’s unique id as a suffix on your feature branch.

So, you have created your my_awesome_new_feature branch and pushed some code on Github, only to realise that you are missing Trello’s card id! How can you rename both your local and remote branch?

First, you want to rename your local branch. As a matter of fact, this step is super simple:

# Create and switch to the new branch
git co -b my_awesome_new_feature
# Push some code on the remote branch on Github
git push origin my_awesome_new_feature
# Rename the local branch
git branch -m my_awesome_new_feature my_awesome_new_feature_abc123

Now, you want to rename the remote branch.

However, you can’t actually rename a remote branch. Instead, you have to delete it and then replace it by pushing the newly renamed branch.

Delete the old remote branch:

# It doesn't matter on what branch you are on
git push origin :my_awesome_new_feature

The only thing left, is to push the renamed branch to Github:

# Switch to the relevant branch
git co my_awesome_new_feature_abc123
# Push the new branch to Github
git push origin my_awesome_new_feature_abc123

Note: If you are renaming a remote branch and you are not the only collaborator on it, it would be wise to inform them in advance that you are about to do so.

And that’s it pretty much.

Bonus: Interested on how you could rename the local branch manually? One way would be to do the following:

# Switch to the branch you want to rename
git co -b my_awesome_new_feature
# Checkout a new branch from current branch. It will carry the history with it.
git co -b my_awesome_new_feature_abc123
# Delete the old branch
git branch -d my_awesome_new_feature

yourname

Keep this sentence less than 13 words or it won't look good.