To rename a local Git branch, use the git branch -m
(or --move
) command. There are two common scenarios:
1. Rename the Current Branch (You’re Checked Out to It)
git branch -m <new-branch-name>
Example:
# Current branch: "old-branch"
git branch -m new-feature
2. Rename Another Local Branch (Not Checked Out)
Specify both the old and new branch names:
git branch -m <old-branch-name> <new-branch-name>
Example:
# Rename "bug-fix" to "hotfix/login"
git branch -m bug-fix hotfix/login
Update the Remote Branch (If Already Pushed)
If the branch was previously pushed to a remote repository (e.g., GitHub/GitLab), you’ll need to:
- Delete the old remote branch:
git push origin --delete <old-branch-name>
- Push the newly renamed branch:
git push origin -u <new-branch-name>
Example Workflow
# 1. Rename the current branch
git branch -m new-feature
# 2. Push the renamed branch to remote and set upstream
git push origin -u new-feature
# 3. Delete the old remote branch (if needed)
git push origin --delete old-branch
Notes
- Branch Name Conflicts: Git will throw an error if the new name already exists locally.
- Collaborators: If others use the old branch, they’ll need to update their local references.
- Force Rename: Use
-M
(uppercase) to force rename even if the new name exists (use with caution!).
By following these steps, you can safely rename branches and keep your repository organized!