How to Set Default Branch Name in Git
To set the default branch name for new Git repositories, use
git config --global init.defaultBranch <branch-name>. To rename the default branch in an existing repository, use git branch -m <old-name> <new-name> and update remote settings accordingly.Syntax
There are two main ways to set the default branch name in Git:
- For new repositories: Set the global default branch name using
git config --global init.defaultBranch <branch-name>. - For existing repositories: Rename the current branch using
git branch -m <old-name> <new-name>and update the remote branch.
This controls what branch Git creates or uses by default.
bash
git config --global init.defaultBranch <branch-name>
git branch -m <old-name> <new-name>Example
This example shows how to set the default branch name to main for new repositories and rename an existing branch from master to main.
bash
# Set default branch for new repos git config --global init.defaultBranch main # Rename branch in existing repo git branch -m master main # Push renamed branch and reset upstream git push -u origin main git push origin --delete master
Output
Branch renamed from 'master' to 'main'.
New branch 'main' pushed and set as upstream.
Old branch 'master' deleted from remote.
Common Pitfalls
Common mistakes when setting default branch name include:
- Not setting
init.defaultBranchglobally, so new repos still default tomaster. - Renaming the branch locally but forgetting to update the remote branch and upstream tracking.
- Not informing collaborators about the branch name change, causing confusion.
Always push the renamed branch and delete the old remote branch to avoid conflicts.
bash
## Wrong: Renaming branch locally only git branch -m master main ## Right: Rename, push, and delete old remote branch git branch -m master main git push -u origin main git push origin --delete master
Quick Reference
| Command | Purpose |
|---|---|
| git config --global init.defaultBranch | Set default branch name for new repos |
| git branch -m | Rename branch locally |
| git push -u origin | Push renamed branch and set upstream |
| git push origin --delete | Delete old branch from remote |
Key Takeaways
Use 'git config --global init.defaultBranch ' to set default branch for new repos.
Rename existing branches with 'git branch -m' and update remote branches accordingly.
Always push the renamed branch and delete the old remote branch to avoid confusion.
Inform your team about branch name changes to keep collaboration smooth.