Changing default git branch to main locally

prathamesh

Prathamesh Sonpatki

Posted on May 24, 2021

Changing default git branch to main locally

git main branch

GitHub has shifted to main branch for new projects but when creating a new project locally with git init still creates master branch. In this post, we will see how to create main branch locally by default.

The git init command accepts value for name of the branch in the -b flag.

$ git init -b main
Initialized empty Git repository in /private/tmp/food/.git/
$ touch tmp.txt
$ git add .
$ git commit -m "main"
[main (root-commit) 0b3550b] main
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 tmp.txt
Enter fullscreen mode Exit fullscreen mode

This is possible only with Git 2.24 onwards.

We can also configure the default branch globally.

git config --global init.defaultBranch main
Enter fullscreen mode Exit fullscreen mode

For older Git versions, we can switch to the main branch before committing anything because the branch doesn't exist for real until something is committed.

cd sport
git init
git branch -m main
Enter fullscreen mode Exit fullscreen mode

My git version was 2.31.1 while writing this post.

git --version
git version 2.31.1
Enter fullscreen mode Exit fullscreen mode
πŸ’– πŸ’ͺ πŸ™… 🚩
prathamesh
Prathamesh Sonpatki

Posted on May 24, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related