How to rename a local and remote Git branch

In this article, we will learn how we can rename a git branch locally and remotely.

Sometimes while working on a project with git, we might make some typos while naming our branches on Github. And to fix the spellings of our branch we have to rename it.

So here are the steps you can follow to rename your branch locally on your machine or remotely on your git repository.

How to rename a local git branch?

If you are on the same branch that you want to rename:

git branch -m <new-name>

The -m flag is the move command to rename any branch in git. You can also use --move in place of -m.

If you are on a different branch then you can use this:

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

Suppose I am currently on master branch and I want to rename a different branch named branchTwo to branch-two then:

git branch -m branchTwo branch-two

How to rename a remote branch in git

If you want to rename a remote branch then we have to do the same process as above locally and then push the local branch and reset the upstream branch.

Let's say we have three branches in our repository.

rename local and remote git branch

Now I want to rename remote branch branchOne to branch-one locally first from master branch

git branch -m branchOne branch-one

Now we can push the branch with the new name to a remote repository like this

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

Here, we will push theΒ new-name branch: branch-one

git push origin -u branch-one

Once we push the branch we will see the this in the remote repo:

rename remote git branch

As we can see we have both the branch-one (new branch) and the branchOne (old branch) in the remote repo.

Now we will delete the old branch from the remote repository

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

Here, we will delete the old branch : branchOne

git push origin --delete branchOne

Alternative way to delete the old branch and reset the upstream branch in remote repo

There is an easy way to push and delete the old branch in one line.

git push origin :old-branch-name new-branch-name

If we take the above example then it will be like this

git push origin :branchOne branch-one

This code will delete the old-name remote branch and push the new-name local branch.

Next, you just need to reset the upstream branch for the new-name branch.

Just switch to the branch and type:

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

Now the remote old branch will be deleted from the repository.

delete remote git branch

πŸ’Ύ Recommended Articles