Rename Local and Remote branch in git
Many time developers accidentally make a typo while naming the git branch locally and sometimes we push the code to remote git branch without realization. In this case you need to rectify the mistake before the peer review happens for not following a proper naming conventions.
In this article we will look at the git commands to rename branch in local and remote.
1. Rename your local branch.
If you are on the same branch which you want to rename
git branch -m new-name
If you are on a different branch
git branch -m old-name new-name
2: Pushing changes to the remote
If the renamed branch is not pushed to remote repository then you can simply push it by using below command
git push origin new-name
If you have already pushed the branch to remote and now if you want to rename the remote branch then you need to delete the old branch and push the renamed branch.
3. Delete the old-name remote branch and push the new-name local branch.
git push origin :old-name new-name
4. Reset the upstream branch for the new-name local branch.
Switch to the branch then
git push origin -u new-name
In simple you can run the following git rename branch commands
Step 1- Rename the old branch name with new name
Step 2- Delete the old branch
Step 3- Push the new branch and set upstream local branch to track the new remote branch
git branch -m old_branch new_branch # Rename branch locally
git push origin :old_branch # Delete the old branch
git push --set-upstream origin new_branch # Push the new branch, set local branch to track the new remote