How do I rename a local Git branch?

 

You can rename a local Git branch using the git branch command along with the -m option (short for "move"). Here's how to rename a local Git branch with an example:

Suppose you have a local branch named old-branch-name, and you want to rename it to new-branch-name.

  1. Ensure You Are on a Different Branch:

    Before renaming the branch, make sure you are not currently on the branch you intend to rename. You can switch to a different branch using the git checkout command:

    bash
  • git checkout some-other-branch
  • Rename the Branch:

    Use the git branch -m command to rename the local branch:

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

    Replace old-branch-name with the current name of the branch you want to rename and new-branch-name with the new name you want to give to the branch.

  • Check the Branch Name Change:

    You can use the git branch command with no arguments to list all local branches and verify that the branch has been renamed:

    bash
    1. git branch

      The branch list should now show the new-branch-name.

    Here's an example of how to rename a local Git branch:

    bash
    # Ensure you are on a different branch (not the one you want to rename) git checkout main # Rename the branch git branch -m old-branch-name new-branch-name # Verify the branch name change git branch

    After running these commands, the branch old-branch-name will be renamed to new-branch-name. Please note that this only renames the local branch. If the branch has been pushed to a remote repository, you may also need to update the remote branch name, which can be done using the git push command with the --delete and --set-upstream options. Be cautious when renaming branches in a shared repository, as it can affect collaboration with other team members.

    Comments