How to Rename Local and Remote Git Branch

Ashok Chapagai Feb 02, 2024
  1. Rename the Currently Active Git Local Branch
  2. Rename a Non-Active Git Branch
  3. Rename a Git Remote Branch
How to Rename Local and Remote Git Branch

While working on a project, if you ever feel like the branch name is not suitable for the branch you are working on, and want to rename the branch, then there are a few ways to rename the branch depending upon the different scenarios you are on. In this article, we look into how to rename the branch either in a local machine or if the branch is in the remote repository.

Rename the Currently Active Git Local Branch

The syntax for renaming the currently active branch is below.

git branch -m <New_Branch_Name>

For example, if we are currently working on branch name bug-fix and need to change the name to bug-fix-1, we can use the following syntax to rename the branch.

git branch -m bug-fix-1
Note
The -m flag is the short form of --move, which acts similarly to the mv command.

However, with this method, if we push changes to the remote repository, a new branch with the changes will be created, and the old one will remain as it is.

Rename a Non-Active Git Branch

If we are working in a branch master and need to rename another branch named bug-fix to bug-fix-1 , we can follow the following syntax.

git branch -m <Old_Branch_Name> <New_Branch_Name>

For example,

git branch -m bug-fix bug-fix-1
Note
With git, we can also set an alias to make use of git commands easily as below.
git config --global alias.rename 'branch -m'

Now, with the alias set, we can use the following syntax to rename the git branch.

git rename <New_Name> # If Renaming Currently Active Branch

Or,

git rename <Old_Name> <New_Name> # If Renaming a Not Active Branch

Rename a Git Remote Branch

If we want to rename a remote branch, then we need to follow three steps instead.

  • Rename the branch name locally.
    git branch -m <New_Branch_Name>
    # OR
    git branch -m <Old_Branch_Name> <New_Branch_Name>
    
  • Push the changes in branch name to the remote repository.
    git push origin :<Old_Branch_Name> <New_Branch_Name>
    

    Note: The colon (:), in front of <Old_Branch_Name>, should not be missed.

  • Set local branch to track the remote repository with the same name, for that, we need to use the following syntax.
    git push --set-upstream origin <New_Branch_Name>
    
Ashok Chapagai avatar Ashok Chapagai avatar

Ashok is an avid learner and senior software engineer with a keen interest in cyber security. He loves articulating his experience with words to wider audience.

LinkedIn GitHub

Related Article - Git Branch