Signup/Sign In

How to Change Branch Name in Git

Branches are an important part of any Git repository. They help the developers by providing them an independent environment to build features without worrying about affecting the rest of the project. There may be cases when we want to rename an existing branch so that it better describes what the branch is about. Let's learn how to rename Git branches.

Renaming Master Branch

Renaming Branches

Branches can be renamed by using the Git Branch command with the -m flag. Remember to first navigate to the branch whose name you wish to change. This can be done by using the Git Checkout command or the Git Switch command.

Renaming Local Branches

The following command will rename the currently checked-out branch.

$ git branch -m <new-branch-name>

We can also use the above command to rename a branch without switching to that branch. We just need to mention the old branch name along with the new name.

$ git branch -m <old-name> <new-name>

Use the Git Branch command to check whether the name was updated or not. Consider the following example where we are trying to change the name of a branch.

We first use the Git Branch command to see the current branch name(oldName) in this case.

Viewing the old name of the branch

Next, we update the name using the -m flag with Git Branch.

Changing the branch name

To check whether the name was updated run the Git Branch command again.

Viewing the updated branch name

Renaming Remote Branches

Our local branch may have a corresponding branch with the same name in the remote repository. Having different names for branches in the local and remote repositories may lead to confusion while pushing or pulling. It is important to rename the corresponding remote branch when updating the name of the local branch.

Use the Git Push command with the -u flag after renaming the local branch by using the above-mentioned command. This will create a new remote branch with a new name. The -u flag is used to set the remote branch as the upstream branch for our local branch.

$ git push -u <remote> <new-name>

Now, we need to remove the branch with the old name from the remote repository. Use the --delete option with Git Push to do this.

$ git push --delete <remote> <old-name>

Summary

Branches are very useful when developing new features or experimenting with our project. Each branch is identified with its unique name and there may be cases where we need to rename our branches. The Git Branch command can be used to rename the branch. If we are working with a remote repository then it is important to push our local changes to the remote. After renaming a branch use the Git Push command to push the new branch to the remote repository and then delete the existing remote branch with the old name.