0
0
GitHow-ToBeginner · 3 min read

How to Rename a Local Branch in Git Quickly and Safely

To rename a local branch in Git, use the command git branch -m old-branch-name new-branch-name. If you are on the branch you want to rename, you can omit the old name and just run git branch -m new-branch-name.
📐

Syntax

The basic syntax to rename a local branch in Git is:

  • git branch -m old-branch-name new-branch-name: Rename a branch from old-branch-name to new-branch-name.
  • git branch -m new-branch-name: Rename the current branch to new-branch-name.

The -m flag stands for "move" and is used to rename branches.

bash
git branch -m old-branch-name new-branch-name

git branch -m new-branch-name
💻

Example

This example shows how to rename a local branch named feature1 to feature-renamed. It also shows how to rename the current branch without specifying the old name.

bash
# Rename a branch when you are NOT on it
git branch -m feature1 feature-renamed

# Rename the current branch to 'new-feature'
git branch -m new-feature
Output
Renamed branch 'feature1' to 'feature-renamed' Renamed branch 'feature1' to 'new-feature'
⚠️

Common Pitfalls

Common mistakes when renaming branches include:

  • Trying to rename a branch that does not exist.
  • Renaming a branch to a name that already exists.
  • Not updating remote branches after renaming locally.

Remember, renaming a local branch does not rename the branch on the remote repository. You need to delete the old remote branch and push the renamed branch if you want to update it remotely.

bash
# Wrong: Renaming a non-existent branch
$ git branch -m no-branch new-name
error: branch 'no-branch' not found.

# Right: Rename existing branch
$ git branch -m old-name new-name
Output
error: branch 'no-branch' not found.
📊

Quick Reference

CommandDescription
git branch -m old-name new-nameRename a branch from old-name to new-name
git branch -m new-nameRename the current branch to new-name
git push origin :old-nameDelete old branch on remote
git push origin new-namePush renamed branch to remote
git push origin -u new-namePush renamed branch and set upstream

Key Takeaways

Use git branch -m to rename local branches safely.
If on the branch to rename, omit the old branch name in the command.
Renaming locally does not affect remote branches automatically.
Delete the old remote branch and push the renamed branch to update remote.
Avoid renaming to a branch name that already exists.