Join my free Bash scripting course on Udemy 👀

Use -m or -M to rename a local git branch

May 19, 2022  ‐ 2 min read

Branch names in git are not at all static. Especially if you have not yet pushed a branch to a git remote you are free to rename your branches as often as you like. In my workflow I often prefix branch names with wip- while working on a new feature.

First we will checkout the branch we wish to rename, use git checkout as the first step:

$ git checkout wip-new-feature
$ git branch --show-current
wip-new-feature

Now that we are on the branch we wish to rename we can use the -m option of the branch subcommand to give the branch a new name. The -m option is actually short for --move, that might make it easier to remember.

To move the current git branch to a new name you use the command git branch -m <new-name>. See the following example:

$ git branch --show-current
wip-new-feature
$ git branch -m new-feature
$ git branch --show-current
new-feature

Force a new name

If you already have a branch with this name you may encounter an error saying that a branch with that name already exists.

$ git branch -m new-feature
fatal: A branch named 'new-feature' already exists.

You have different ways to get around this error. Obviously you can rename the other branch first using the steps shown above. Or you can force the rename, by using the --force option or -M (capital m).

$ git branch -M new-feature

Renaming branches directly

Although we chose to checkout the branch we wished to rename, this is not mandatory. We can rename a branch as well by supplying both the current branch name and the new branch name.

$ git branch -m  wip-new-feature new-feature

Push a renamed branch

All the examples above only move the local branch to a new name. To have this newly named branch on our remote as well we need to push the branch. We will do so while directly setting the upstream branch we track:

$ git push origin -u new-feature

The second step is to remove the old name from the remote. But you want to have some caution here. If team members or your continuous integration solution relies on this branch don't just delete it.

If that is all taken care of you can remove the remote branch as follows:

$ git push origin --delete wip-new-feature