How to rename a Git branch (locally and remotely)

You want to rename a Git branch because of a typo or for any other reason? What if you already have pushed to the origin?

In this article we check the available Git commands to achieve these tasks.

Rename a local branch

If you want to rename the branch that you are currently on, run:

git branch -m <new-branch-name>

If you want to rename another local branch while you are on a different branch, use:

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

This changes the local branch name only. It does not affect the remote branch yet.

Note on capitalization changes

If you are only changing the capitalization of your branch name (e.g., bugfix to BugFix) on Windows or macOS, Git might throw an error because of case-insensitive file systems. To force the rename, use a capital -M:

git branch -M <new-branch-name>

Rename a branch after it has been pushed

If the branch already exists on the remote repository, you need to update the remote as well.

  1. Delete the old branch from the remote:
git push origin --delete <old-branch-name>
  1. Push the new branch and set it as the upstream branch:
git push origin -u <new-branch-name>

This creates the new remote branch and links your local branch to it.

Remember that you cannot delete an active default branch via the command line. For example renaming from the default master to main. You will have to change the default branch to the one you created. You can do that in the repository settings.

Verify the result

You can confirm that everything is correct and linked properly by running:

git branch -vv

This command lists your local branches, their latest commits, and the upstream remote branches they are tracking.

comments powered by Disqus