When you want to change the name of a Git branch, follow these steps and commands:
- Check the current branch:
Ensure you are on the correct branch. Use the following command to view your current branch:
bashgit branch
This command lists all branches and prefixes the current branch with an asterisk.
- Rename the branch:
If you are on the branch you want to rename, use this command:
bashgit 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:
bashgit branch -m old-branch-name new-branch-name
- 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:
bashgit 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.
- Update the remote tracking branch reference:
If your local branch tracks a remote branch, set the new upstream branch:
bashgit 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:
- First, ensure you are not on the
feature-oldbranch, or if you are, directly rename it:
bashgit branch -m feature-new
- Delete the old remote branch and push the new branch name:
bashgit push origin --delete feature-old git push origin feature-new
- Set the new upstream branch:
bashgit push --set-upstream origin feature-new
Using these steps, you can effectively rename the Git branch and ensure the remote repository is updated synchronously.