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-featuretofeature/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:
- Rename the branch locally:
git branch -m <new-branch-name> - Delete the old branch from the remote:
git push origin --delete <old-branch-name> - Push the new branch to the remote:
git push origin <new-branch-name> - 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:
- Rename the branch locally:
git branch -m feature/new-feature - Delete the old branch on the remote:
git push origin --delete feature/old-feature - Push the new branch to the remote:
git push origin feature/new-feature - 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
| Action | Command |
|---|---|
| Rename the current branch | git branch -m <new-branch-name> |
| Rename a non-current branch | git branch -m <old-branch-name> <new-branch-name> |
| Delete old branch on remote | git push origin --delete <old-branch-name> |
| Push new branch to remote | git push origin <new-branch-name> |
| Set the upstream tracking reference | git push --set-upstream origin <new-branch-name> |
| List local branches to verify | git branch |
No images available.