How to rename a local Git branch?

To rename a local Git branch, you can use the git branch -m command.


1. Rename the Current Branch

If you want to rename the branch you’re currently working on, use the git branch -m command followed by the new branch name.

Command:

git branch -m <new-branch-name>

Example:

If you’re on the feature/old-feature branch and want to rename it to feature/new-feature:

git branch -m feature/new-feature
  • Effect: This renames the current branch to feature/new-feature.

2. Rename a Different (Non-Current) Branch

If you’re not on the branch you want to rename, you can still rename it by specifying the old branch name and the new one.

Command:

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

Example:

If you are currently on main but want to rename feature/old-feature to feature/new-feature:

git branch -m feature/old-feature feature/new-feature
  • Effect: This renames feature/old-feature to feature/new-feature, even though you are on a different branch.

3. Rename a Branch and Push to Remote

After renaming a branch locally, you might also want to update the remote repository to reflect the new branch name.

Steps:

  1. Rename the branch locally:
    git branch -m <new-branch-name>
  2. Delete the old branch from the remote:
    git push origin --delete <old-branch-name>
  3. Push the new branch to the remote:
    git push origin <new-branch-name>
  4. Reset the upstream tracking reference (if you want the new branch to track the remote branch):
    git push --set-upstream origin <new-branch-name>

Example:

Renaming feature/old-feature to feature/new-feature and pushing it to the remote:

  1. Rename the branch locally:
    git branch -m feature/new-feature
  2. Delete the old branch on the remote:
    git push origin --delete feature/old-feature
  3. Push the new branch to the remote:
    git push origin feature/new-feature
  4. Set the upstream for the new branch:
    git push --set-upstream origin feature/new-feature

4. Check if the Rename Was Successful

To confirm that the branch has been renamed, you can list all local branches:

git branch

You should see the renamed branch in the list.


Summary of Commands

ActionCommand
Rename the current branchgit branch -m <new-branch-name>
Rename a non-current branchgit branch -m <old-branch-name> <new-branch-name>
Delete old branch on remotegit push origin --delete <old-branch-name>
Push new branch to remotegit push origin <new-branch-name>
Set the upstream tracking referencegit push --set-upstream origin <new-branch-name>
List local branches to verifygit branch

No images available.