How to rename a git branch

How to rename a git branch

In this article lets understand how to rename a git branch.

So, there can be two types of situations where you will have only local branch to rename or the branch you have already pushed to the remote repository.

  1. In first case where you only have local branch you can rename and that’s it. Will see in this article how.
  2. In second case what you will need to do is rename local branch then push it to the remote and then delete the old branch.

Let’s understand how to do it. Follow below steps:

1 ) Move to another branch.

Although not technically necessary, this procedure can help avoid potential problems. So before rename switch to another branch as below.

git checkout <some-other-branch>
  • <some-other-branch> – will be any other random branch from your repository.

Lets say it “task1”

git checkout task1

2 ) Rename the branch

Use below command to rename from old branch to new branch:

git branch -m <old-branch> <new-branch>
  • <old-branch> – will be the name of your existing branch you want to rename. Lets say task2-withchanges
  • <new-branch> – will be the name of what you want to rename to. Lets say task2

git branch -m task2-withchanges task2

Use the -m or --move option with the branch command to rename the branch as above.

Now, if you have not switched as mentioned above and you are on branch you want to rename (already on task2-withchanges) , you can skip mention of old branch.

git branch -m <new-branch-name>

git branch -m task2

3 ) Push new branch

Now you will need to push the renamed branch to remote. Use below command:

git push origin -u <new-branch-name>

git push origin -u task2

The -u or --set-upstream option is used to set the upstream branch for the new name, allowing you to use git pull and git push without specifying the branch name in the future.

4 ) Optional – delete old branch from repo

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

git push origin –delete task2-withchanges

If you had the remote branch as well , you may wish to delete it from remote repo using above command.

Keep in mind that changing a branch’s name only affects the branch’s local and remote references. The branch’s content and commit history are unchanged.

That’s all on how to rename a git branch. Hope this find you helpful.

Read more articles on git here.