乐闻世界logo
搜索文章和话题

How to Rename a Branch with Git?

2024年7月4日 09:38

When you want to change the name of a Git branch, follow these steps and commands:

  1. Check the current branch:

Ensure you are on the correct branch. Use the following command to view your current branch:

bash
git branch

This command lists all branches and prefixes the current branch with an asterisk.

  1. Rename the branch:

If you are on the branch you want to rename, use this command:

bash
git branch -m new-branch-name

-m is an abbreviation for 'move', meaning moving or renaming the branch.

If you are not on the branch you want to rename, specify the old branch name and the new branch name:

bash
git branch -m old-branch-name new-branch-name
  1. If the branch has been pushed to a remote repository:

In this case, first delete the old remote branch, then push the new branch name:

bash
git push origin --delete old-branch-name git push origin new-branch-name

Here, delete the old branch from the remote repository first, then push the new branch name.

  1. Update the remote tracking branch reference:

If your local branch tracks a remote branch, set the new upstream branch:

bash
git push --set-upstream origin new-branch-name

Example:

Suppose you have a branch named feature-old that you want to rename to feature-new, and it has already been pushed to the remote repository:

  1. First, ensure you are not on the feature-old branch, or if you are, directly rename it:
bash
git branch -m feature-new
  1. Delete the old remote branch and push the new branch name:
bash
git push origin --delete feature-old git push origin feature-new
  1. Set the new upstream branch:
bash
git push --set-upstream origin feature-new

Using these steps, you can effectively rename the Git branch and ensure the remote repository is updated synchronously.

标签:Git