In some cases, such as when you have named a branch that does not conform to the project standard, you need to rename it.
It's a super simple task, but often developers forget either the commands or the exact order of arguments and they have to spend time googling it.
To rename local branch, follow these steps:
git checkout <old_name>
git branch -m <new_name>
The -m flag stands for (--move) and it is used to move/rename a branch and a corresponding reflog entry.
If the branch with a new_name already exists, you should use -M (--move --force) flag to force the rename.
Sometimes you can't move to the branch you want to rename.
The good thing is that you don't have to, use the following command:
git branch -m <old_name> <new_name>
Once you've managed to push the branch you want to rename to the remote branch, things get a little more complicated because you have to remember to change the upstream as well.
Given you have renamed the branch locally:
git push origin -u <new_name>
git push origin -d <old_name>
Working with branches in Git is an essential part of a successful software development process and knowing how to rename them properly is a must, as mistakes happen far too often.
Renaming a local branch is a matter of just one command, but if the branch has been pushed to a remote, then you need to push the renamed local branch and delete the branch with the old name.