How to rename git branch

To make it short, the main take-aways:

git branch -m <new-name>
git branch -m <old-name> <new-name>
git push origin -u <new-name>
git push origin -d <old-name>

Use case: local changes or project not yet existing on remote

To rename the current git branch:

git branch -m <new-name>

To rename any other git branches you’re not currently pointing at:

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

Tips:

  • The -m option is short for --move. That way it’s easier to remember.
  • Other custom-made shortcuts can be defined e.g. typing git b for git branch. Check How to create Git Aliases.

Use case: git project already deployed

If your git project is already deployed on a remote environment – e.g. Gitlab or Github – the beforementioned changes won’t be reflected though. To change the branches not only on local but also on the remote, you need to:

First, push the local branch and reset the upstream branch:

git push origin -u <new-name>

Then, delete the remote branch:

git push origin --delete <old-name>

Note: in that case, it is not necessary to use the git branch -m commands.

Use case: changing the capitalization

If you are only changing the capitalization – e.g. dev/vers-5395 becoming dev/VERS-5395 – you need to use -M instead of -m as Git will tell you that the branch already exists otherwise. This matters for users being on Windows or any other case-insensitive file systems.

Note: if you are wondering what might be a good branch naming convention, you can check the git branch naming conventions article.

Example

Github then Gitlab recently introduced changes to their main branch naming convention. By default, drifting from master to main. If you are a person used to the traditional way, you can restore the branch name, turning things more into your likings:

> git clone git@gitlab.com:username/your-project-in-kebab-case.git
> git branch
* main
> git push origin -u master
> git push origin --delete main

You can then check your changes:

> git branch
* master

Run the extra mile

If like me you’re still not 100% sure when it comes to git stash, rebase, forking and traveling back the history line, you can either:

But remember: it’s a marathon, not a sprint 🐢

Leave a Reply

Your email address will not be published. Required fields are marked *