Renaming a branch in Git differs slightly depending on whether you're renaming the current branch or one you’re not currently pointed to.
Renaming the current branch
To rename the current branch, you simply use the
branch
command with the--move
flag:git branch --move <new-branch-name>
Renaming a branch you aren’t pointed to
If you want to rename a branch that you're not currently on, you'll need to specify both the old branch name and the new branch name in the command:
git branch --move <old-branch-name> <new-branch-name>
Note: If the name change only changes capitalization and you’re using a case-insensitive filesystem like Windows, add the --force
flag otherwise Git will return a branch already exists
error. The --force
flag will ensure that the “existing” branch is updated with the new name.
Pushing the renamed branch to a remote
If the branch you renamed already exists in the remote repository, you'll need to delete the old branch from the remote and push the new one.
Delete the old branch from the remote:
git push origin --delete <old-branch-name>
Push the new branch to the remote and reset the upstream branch:
git push origin -u <new-branch-name>
This process effectively renames the branch both locally and on the remote. Remember to let your team know about the change if you're working in a shared repository, as they'll need to adjust their local branches accordingly.
For additional reading on git branch management please see the official documentation.