Have you ever been in a position where the name of a branch is no longer relevant? Have you noticed a typo in the names of one of your branches that you just can’t stop thinking about? There’s good news for you: Git allows you to rename a branch.
In this tutorial, we’re going to talk about how to rename a Git branch. We’ll walk though an example of renaming a local and remote branch to help you get started.
Without further ado, let’s begin!
Branches are independent lines of development in a Git repository. They are used to separate your code so that you can work on different parts of a project without having to affect the main line of development.
What happens if a branch is named incorrectly? Do you need to delete it? No. Git may be annoying at times but it does have a method that you can use to rename a branch. You can learn more about Git branches in our git branch tutorial.
Git Rename Branch
You can rename a local and remote branch using the branch command.
First, you’ve got to navigate to the branch that you want to rename. You can do this using the git checkout command:
git checkout fix-bug-22
This command allows us to view the branch fix-bug-22. We’ve just noticed that this branch is actually for fixing bug 23, not bug 22. We can rectify this mistake by using the git branch command with the -m flag to rename the branch:
git branch -m fix-bug-23
The name of the branch has been successfully changed.
Git Rename Remote Branch
To rename a remote branch, you need to push a new version of a branch to a remote repository.
The first step is to rename a branch using the instructions from our last example. Then, you can push the new branch to your remote repository using git push:
git push origin -u fix-bug-23
This adds the branch fix-bug-23 to the remote repository with the name “origin”.
When you view your remote repository, the new branch will be visible. However, the old branch will still be visible. To fix this, you should delete the old branch from your remote repository using the git command line:
git push origin --delete fix-bug-22
This will delete the branch fix-bug-22 from your remote repository. Once you run that command, you’ll have a new branch called fix-bug-23 on your master, and no branch called fix-bug-22.
Branches help developers keep their code separate. They are useful because they allow developers to work on multiple different features and bug reports without having to change the main line of development every time they need to commit their code.
To rename a git branch, you can use the git branch -m command. Now you’re ready to start renaming a remote Git branch and a local Git branch like an expert!