This post will discuss how to rename a Git branch locally and remotely.

We may want to rename a Git branch, either because we made a typo, changed our mind, or want to follow a naming convention. Renaming a Git branch can be done both locally and remotely:

1. Renaming a Local Branch

To rename a local branch, we can use the git-branch command with the -m or -M option. We can use the -m option in two ways:

  1. To rename the current branch that we have checked out, we can simply pass the new name as an argument:

    git branch (-m | -M) <newbranch>

  2. To rename another branch that we are not on, we need to pass both the old name and the new name as arguments:

    git branch (-m | -M) [<oldbranch>] <newbranch>

Here, -m is an alias for --move, which moves or renames a branch. And -M is an alias for --move --force, which forces the rename to happen when a new branch already exists. The -M option is often useful when changing the branch’s case since git will complain that the branch already exists. When the old branch name is not specified, it renames the current branch to a new name.

2. Renaming a Remote Branch

After renaming the local branch, we have to propagate the changes to the remote server as well. The idea is to delete the old branch from the remote Git repository after renaming, push the local, new branch, and set up the local branch to track the remote branch.

# Rename the local branch
$ git branch -m <newbranch>
 
# Delete the old branch on the remote
$ git push <remote> :<oldbranch>
 
# or use --delete
# $ git push <remote> --delete <oldbranch>
 
# Push the new branch, and set up the local branch to track the remote branch
$ git push --set-upstream <remote> <newbranch>

Here’s a live example:

git branch -m

That’s all about renaming a Git branch.