How to Rename Local and Remote Git Branches

Hero image for How to Rename Local and Remote Git Branches. Image by hati.royani.
Hero image for 'How to Rename Local and Remote Git Branches.' Image by hati.royani.

Maybe you're working in a Git repo with a specific naming convention, and you misname the branch you're working on. Perhaps you've been hit by an unfortunate typo. Either way, you need to rename your local branch and maybe even on the remote. Here's how you do that.

Switch to the branch that you need to update, and run:

git checkout old-branch-namegit branch -m updated-branch-name

This renames your local copy of the current branch. You can also do this without first checking out the local branch as a oneliner like this:

git branch -m old-branch-name updated-branch-name

Then, to get this updated name pushed through to the remote, you need to delete the old remote branch and push your new one in its place.

There are a few ways you can achieve this, but here's the oneliner I have in my Terminal history:

git push origin :old-branch-name updated-branch-name

Then, you need to check out the new remote branch that you've created:

git checkout updated-branch-name

And then set the upstream branch to be the new remote branch that you've created. Again, here's the shorthand way to do that:

git push origin -u updated-branch-name

And you're done! You've:

  1. renamed your local branch,
  2. deleted the branch with the old name from the remote,
  3. replaced it with a branch with the updated name that you need to use,
  4. and reset your upstream branch so that future pushes go to the new branch.

Renaming on Git is a little bit of a longwinded process, but once you consider how source control works, and the intention behind it, you can pretty easily see how it's a better way forward than just renaming branches; it keeps things clear when looking through branch and repo history, and prevents naming confusion.


Categories:

  1. Git
  2. Guides