Renaming Branches
Sometimes you need to rename a branch - maybe there's a typo, or you want to follow a naming convention.
Rename Current Branch
Using -m Flag
bash
1# First, switch to the branch you want to rename
2git checkout old-branch-name
3
4# Rename the current branch
5git branch -m new-branch-nameExample
bash
1# You're on 'feture-login' (typo!)
2git branch
3# * feture-login
4
5# Rename to fix the typo
6git branch -m feature-login
7
8# Verify
9git branch
10# * feature-loginRename a Different Branch
You can rename a branch you're not currently on:
bash
1# Rename any branch (don't need to be on it)
2git branch -m old-name new-nameExample
bash
1# You're on main, want to rename feature-1
2git branch
3# * main
4# feature-1
5
6# Rename feature-1 to feature-user-auth
7git branch -m feature-1 feature-user-auth
8
9# Verify
10git branch
11# * main
12# feature-user-authForce Rename
If a branch with the new name already exists, use -M (uppercase):
bash
1# Force rename (overwrites existing branch)
2git branch -M old-name new-name⚠️ Warning: This deletes the existing branch with that name!
Rename Remote Branches
Renaming a remote branch requires a few steps:
Step 1: Rename Local Branch
bash
1# Rename the local branch
2git branch -m old-name new-nameStep 2: Delete Old Remote Branch
bash
1# Delete the old branch on remote
2git push origin --delete old-nameStep 3: Push New Branch
bash
1# Push the renamed branch
2git push origin new-name
3
4# Set upstream
5git push -u origin new-nameComplete Example
bash
1# Rename local branch
2git branch -m feature-old feature-new
3
4# Delete old branch from GitHub
5git push origin --delete feature-old
6
7# Push new branch to GitHub
8git push -u origin feature-newRename main/master Branch
To rename the default branch:
Local Rename
bash
1# Rename master to main
2git branch -m master mainUpdate Remote
bash
1# Push the new main branch
2git push -u origin main
3
4# Delete the old master branch
5git push origin --delete masterUpdate Default on GitHub
- Go to repository Settings
- Click on Branches
- Change default branch to
main - Then delete
master
Verify the Rename
After renaming, verify everything is correct:
bash
1# Check local branches
2git branch
3
4# Check remote branches
5git branch -r
6
7# Check tracking
8git branch -vvCommon Scenarios
Fix a Typo
bash
1# Wrong: feture-login → Right: feature-login
2git branch -m feture-login feature-loginFollow Naming Convention
bash
1# Add prefix for consistency
2git branch -m user-auth feature/user-authRename to Add Ticket Number
bash
1# Add JIRA ticket reference
2git branch -m user-auth JIRA-123-user-authSummary
Renaming branches:
- Local current:
git branch -m new-name - Local other:
git branch -m old-name new-name - Force rename:
git branch -M old-name new-name - Remote: Rename local, delete old remote, push new
Practice this in the next exercise!
