Renaming Local and Remote Git Branches
I recently ran into a situation where I created a new branch, pushed it, and then realized the name wasn’t quite right. Instead of starting from scratch, Git makes it pretty simple to rename both your local branch and the corresponding remote branch.
I’ve run into this issue before but had forgotten how to fix it, so this time I’m writing a quick blog post as a handy reference for myself (and maybe for you too).
Let’s say you created a branch called custom-loader
:
git checkout -b custom-loader
git push origin custom-loader
You’ve pushed it to the remote and started working. But later you decide the name should be custom-load-test
.
Local Repo Remote Repo
----------- -----------
custom-loader ---> origin/custom-loader
Renaming the Local Branch
You can rename your local branch with:
git branch -m custom-load-test
Now locally it’s renamed, but the remote still has the old branch.
Local Repo Remote Repo
----------- -----------
custom-load-test ---> origin/custom-loader
Updating the Remote Branch
Next, push the new branch to the remote:
git push origin custom-load-test
git push --set-upstream origin custom-load-test
Now the remote also has the new branch:
Local Repo Remote Repo
----------- -----------
custom-load-test ---> origin/custom-loader
origin/custom-load-test
Cleaning Up the Old Remote Branch
Finally, delete the old remote branch to avoid confusion:
git push origin --delete custom-loader
Local Repo Remote Repo
----------- -----------
custom-load-test ---> origin/custom-load-test
One-Line Shortcut
If you prefer a single command to handle renaming and pushing:
git push origin :custom-loader custom-load-test
git push --set-upstream origin custom-load-test
The :custom-loader
syntax deletes the old branch while simultaneously creating the new one.