Introduction

Git is a software package used for tracking software as it moves through stages of development. Git uses branching to maintain a central repository of code while creating a copy to make changes on.

In this guide, learn how to change the name of a Git branch on a local system or remote repository.

tutorial on renaming or changing the name of a local and remote branch in git

Prerequisites

Rename a Local Branch

For example, you created a new branch and pushed the changes to your remote repository, only to discover the branch name was incorrect. To rename a branch in Git:

1. Enter the name of the branch you want to change in your command line interface:

git checkout old-branch

You should receive confirmation that the branch is checked out.

System confirms that the branch is checked out

2. Rename the branch by entering the command:

git branch –m new-name

Alternatively, you can use a single command. If you’re not already in the master, switch to it:

git checkout master

Enter the following to change a branch name:

git branch –m old-name new-name

3. Verify the renaming was successful by checking the status :

git branch –a 

The output confirms that the branch was successfully renamed as shown below.

master Git Branch renamed


Note: Replace old-name with the actual name of the branch you want to change. Replace new-name with the name of the branch you want to use going forward.


Rename a Remote Git Branch

There isn’t a way to directly rename a Git branch in a remote repository. You will need to delete the old branch name, then push a branch with the correct name to the remote repository.

1. Verify the local branch has the correct name:

git branch -a

2. Next, delete the branch with the old name on the remote repository:

git push origin ––delete old-name

The output confirms that the branch was deleted.

System confirms old git branch was deleted

3. Finally, push the branch with the correct name, and reset the upstream branch:

git push origin –u new-name

Alternatively, you can overwrite the remote branch with a single command:

git push origin :old-name new-name

Resetting the upstream branch is still required:

git push origin –u new-name

Note: Replace old-name with the actual name you want to change. Replace new-name with the name you want to use going forward.


Conclusion

Now you know how to rename or change the name of a local or remote Git branch, even if it has been loaded on a remote repository.


Next you should also read