How Do You Rename a Branch in Git?

Renaming a branch in Git is a common task, especially when you want to align your branch names with a naming convention or correct a typo. Git makes it easy to rename both local and remote branches.

Renaming a Local Branch

To rename a local branch in Git, follow these steps:

1. Switch to the Branch You Want to Rename

If you are not already on the branch you want to rename, switch to it using:

git checkout <old-branch-name>

2. Rename the Branch

Use the git branch command to rename the branch:

git branch -m <new-branch-name>

This command renames the current branch to the new name.

Renaming a Remote Branch

Renaming a remote branch involves more steps, as Git does not directly support renaming remote branches. Here’s how to do it:

1. Push the Renamed Local Branch

After renaming the local branch, push it to the remote repository:

git push origin <new-branch-name>

2. Delete the Old Branch Name on the Remote

To remove the old branch name from the remote repository, use:

git push origin --delete <old-branch-name>

3. Update the Tracking Branch

If your local branch was tracking the remote branch, you need to reset the upstream branch:

git branch --unset-upstream
git branch -u origin/<new-branch-name>

Verifying the Rename

To ensure that the branch has been successfully renamed both locally and remotely, you can list all branches:

git branch -a

This command will show all local and remote branches, allowing you to verify the change.

Conclusion

Renaming a branch in Git is a straightforward process that can be done locally and propagated to the remote repository. This is particularly useful for maintaining a clear and organized branch structure in your project.