Git: Rename a Local and Remote Branch

Did you make a mistake in naming your Git branch? Or maybe "branch-2" wasn't descriptive enough? Luckily in Git you can rename a local branch pretty easily. And while it is also possible with remote branches, the process is a bit more involved with the use of a workaround, but still works as intended.

In this short article I'll show you how to rename Git branches for both local and remote repositories.

Rename a Local Git Branch

To rename a local branch, you'll want to use the branch command like this:

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

The -m option is an alias for --move, which is analog to the Unix mv command.

Continuing with the convention we saw with the delete branch option, capitalizing the flag as -M, which is an alias for --move --force, allows you to "force" the change. Using the option in this way will let you rename the branch even if the new branch name already exists in your repository.

If you're wanting to rename the branch that is currently checked out, then you can omit the <old-branch-name> option, which looks like this:

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

Rename a Remote Git Branch

Renaming a remote branch is a bit more involved, and isn't actually possible in the same way it is for renaming local branches. To do it, you'll need to rename the local branch, delete the remote branch, and then push the renamed local branch to the remote repo again.

In terms of Git commands, here is how the process looks:

$ git branch -m <old-branch-name> <new-branch-name>
$ git push <remote-repo> -d <old-branch-name>
$ git push <remote-repo> <new-branch-name>
$ git checkout <new-branch-name>
$ git push <remote-repo> -u <new-branch-name>

In plain English, here is what is happening line-by-line:

  1. Rename the local branch using the same method shown the first section
  2. Delete the remote branch that is to be renamed
  3. Push the new branch to the remote repo
  4. Switch to the new branch
  5. Reset the upstream reference for the renamed branch

Once you understand what is going on, it isn't too bad, but it certainly requires more steps than simply renaming a local branch.