Home Cloud How To Rename a Git Branch

How To Rename a Git Branch

by admin
rename git branch

How to Rename a Git Branch

When working with git it is sometimes necessary to rename a git branch. There could be any number of reasons why the branch name needs to be changed, but often this comes about because the scope of the change being made to the code has changed, and therefore the git branch name should be updated to best reflect the reason for the branches existance.

Fortunately, git makes it easy for us to change a branch name! Let’s take a look at an example.

Rename a Local Git Branch

In this example we have a branch called test which we would like to rename to something more suitable, such as wip_feature_auth_module, which better describes the purpose of the branch and the code updates it contains.

To begin, checkout the branch that needs to be renamed:

git checkout test

Next, rename the local branch using the git branch -m command:

git branch -m wip_feature_auth_module

And that’s it. The local git branch has now been renamed. To confirm, list the local git branches using the git branch command:

git branch
  main
* wip_feature_auth_module

Rename a Remote Branch

Now, it’s important to be aware that the change we have made by renaming the git branch, has only applied to the local git branch. We can confirm this by listing the remote git branches:

git branch -r
  origin/HEAD -> origin/main
  origin/main
  origin/test

As you can see, the test branch is present. If we want to rename it to reflect the change we made by renaming the local branch, we need to use the git push command, specifiying the old branch name and the new:

git push origin :"test" "wip_feature_auth_module"
Total 0 (delta 0), reused 0 (delta 0), pack-reused 0
To czxcsw/kubernetes.git
 - [deleted]         test
 * [new branch]      wip_feature_auth_module -> wip_feature_auth_module

From the output of the command, we can see that the test branch has been deleted and a new branch has been created to match the new local branch.

Running a git status at this point will reveal the following:

git status
On branch wip_feature_auth_module
Your branch is based on 'origin/test', but the upstream is gone.

We can update the local branch to use the newly renamed remote branch as its upstream, by running:

git push origin -u wip_feature_auth_module
On branch wip_feature_auth_module
Your branch is up to date with 'origin/wip_feature_auth_module'.

nothing to commit, working tree clean

All done! In this tutorial you have learned how you can rename local git branches and rename remote git branches using the git branch -m command.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More