Renaming a local Git branch is a common task in version control. You can safely rename your current branch or a different local branch using a few simple commands. This guide provides a step-by-step solution to ensure your local and remote repositories stay synchronized.
How to Rename Your Current Git Branch
First, ensure you are on the branch you want to rename. Use the checkout command to switch to it:
git checkout old-branch-nameNext, use the -m flag to rename the branch:
git branch -m new-branch-nameHow to Rename a Different Git Branch
You do not need to check out a branch to rename it. Provide both the old and new names:
git branch -m old-branch-name new-branch-nameForce Renaming a Branch
If the new branch name already exists, Git will block the rename with a fatal error: A branch named ‘new-branch-name’ already exists. You can force the rename using the uppercase -M flag. This overwrites the existing branch. Use this with caution.
git branch -M new-branch-nameUpdating the Upstream Tracking Branch
After renaming a local branch, you must update the remote repository. First, delete the old branch name from the remote server:
git push origin --delete old-branch-nameThen, push the newly renamed branch and reset the upstream tracking link:
git push origin -u new-branch-nameSafety tip: Always communicate branch renames with your team. Teammates must update their local tracking references to avoid pushing to the deleted branch. For further reading, consult the official Git documentation.