0
0
GitHow-ToBeginner · 3 min read

How to Set Default Branch in Git: Simple Steps

To set the default branch in Git locally, use git branch -M <branch-name>. To change the default branch on a remote repository like GitHub, update the default branch setting in the repository settings on the website or use the GitHub CLI.
📐

Syntax

The main command to set or rename the default branch locally is git branch -M <branch-name>. Here:

  • -M forces the rename even if the new branch name exists.
  • <branch-name> is the new default branch name you want, like main or master.

For remote repositories, you usually change the default branch via the hosting service's settings (e.g., GitHub, GitLab).

bash
git branch -M <branch-name>
💻

Example

This example renames the current branch to main locally and pushes it to the remote repository, then sets the upstream branch.

bash
git branch -M main
git push -u origin main
Output
Branch 'main' set up to track remote branch 'main' from 'origin'.
⚠️

Common Pitfalls

One common mistake is renaming the branch locally but forgetting to update the remote repository's default branch setting. This causes confusion when others clone or pull.

Another pitfall is pushing the renamed branch without setting the upstream, which leads to push errors.

bash
git branch -M main
# Wrong: forgetting to push or set upstream
# git push origin main

# Right:
git push -u origin main
📊

Quick Reference

ActionCommand or Step
Rename local branchgit branch -M
Push renamed branch and set upstreamgit push -u origin
Change default branch on GitHubGo to repository Settings > Branches > Default branch
Check current branchgit branch --show-current

Key Takeaways

Use 'git branch -M ' to rename and set the default branch locally.
Always push the renamed branch with '-u' to set the upstream tracking branch.
Update the default branch setting on your remote repository hosting service.
Check your current branch with 'git branch --show-current' before renaming.
For GitHub, change the default branch in repository settings to avoid confusion.