How to Rename Local and Remote Git Branches
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-nameThis renames your local copy of the current branch. You can also do this without first checking out the local branch as a one‑liner like this:
git branch -m old-branch-name updated-branch-nameThen, 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 one‑liner I have in my Terminal history:
git push origin :old-branch-name updated-branch-nameThen, you need to check out the new remote branch that you've created:
git checkout updated-branch-nameAnd 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-nameAnd you're done! You've:
- renamed your local branch,
- deleted the branch with the old name from the remote,
- replaced it with a branch with the updated name that you need to use,
- and reset your upstream branch so that future pushes go to the new branch.
Renaming on Git is a little bit of a long‑winded 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.