git: how to rename a branch (both local and remote)?
To rename a branch in Git, you'll need to follow a series of steps to rename it locally and then update the remote repository to reflect the new branch name. Here’s how you can rename a branch both locally and remotely:
Rename Branch Locally
Switch to the Branch You Want to Rename: First, ensure you are on the branch that you want to rename. Use
git checkoutto switch to the branch:Rename the Branch: Rename the current branch to a new name using
git branch -m(short forgit branch --move):Replace
new-branch-namewith the desired new name for your branch.
Push the Renamed Branch to Remote
Delete the Old Remote Branch: To delete the old branch from the remote repository:
Replace
old-branch-namewith the old name of your branch.Push the Renamed Branch: Push the renamed branch to the remote repository using the
uoption to set up the upstream branch:This command pushes the renamed branch (
new-branch-name) to the remote repository and sets it as the upstream branch so that futuregit pullandgit pushcommands work without specifying the branch name.
Update Local Tracking Branch (if needed)
If you have other local repositories that have the old branch name as a tracking branch, you might want to update them:
This command fetches all branches from the remote repository and prunes any remote-tracking branches that no longer exist on the remote. This ensures that your local tracking branches are updated.
Example Scenario
Let's say you want to rename old-branch to new-branch:
Notes
- Collaboration: Renaming a branch affects its history and can cause issues for collaborators who have checked out the old branch. Communicate with your team before renaming branches to avoid confusion.
- History: Renaming a branch does not change its commit history; it only changes the branch name and its references.
By following these steps, you can safely rename a Git branch both locally and on the remote repository, ensuring consistency and clarity in your branch naming conventions.