git,

Rename a Git branch

Apr 30, 2022 · 1 min read · Post a comment
Rename a Git branch

There might be a case where you need to rename a current branch you are already working on, and I’m gonna show you the least painful way to do so. Now, the most common reason is of course mislabeling it due to a Git naming strategy, which might include a Jira story name with number in it. So, unless you are a GIGACHAD and name branches whatever you feel like, this is the tutorial for you.

Prerequisites

  • Git

Solution

Step 1. Open Terminal in your git repo directory and run the following command:

git branch -m <old_branch_name> <new_branch_name>

Note(s). If you already checked out the branch you wanna rename it, just run git branch -m <new_branch_name> and skip to Step 3.

Step 2 (Optional). Checkout the renamed branch.

git checkout <new_branch_name>

Step 3. Delete the old-name remote branch and push the new one.

git push origin :<old_branch_name> <new_branch_name>

Step 4. Reset the upstream branch.

git push origin -u <new_branch_name>

Note(s). Few things to consider:

  1. On Windows, if you face any error messages, use parameter -M instead, otherwise stick to the steps above.
  2. Never delete a remote branch. It’s an anti-pattern to do so.

Conclusion

As always, if you can think of any alternative solution, feel free to write a comment below. On a side note, follow our official channel on Telegram.