Usually, when we initialize a new local Git repository, it creates a conventional branch called the master branch. However, we can easily and completely change this behavior or even rename existing master branches into main branches. Currently, almost all the major Git hosting providers like Github and Gitlab initiate their new Git repositories with main branches as the primary branch. But old Git repositories still have master branches and when we initiate new local Git repositories, they also create a master branch. So let's see how to rename all of these master branches to main branches.

Initialize A New Git Repository With The “main” Branch

If you are initializing a new local Git repository, you can instruct git init to initialize it with a main branch instead of the default master branch.

git init -b main

Configure Git To Initialize New Repositories With “main” Branches

The problem with the above-mentioned git init -b main command is, that you need to mention the branch name (main) every time when you initialize a new Git repository. But we can configure Git to initialize new repositories with a predefined branch name. In this case, main

git config --global init.defaultBranch main

Now, when you initialize a new Git repository with the git init command, it will create a main branch instead of the default master branch.

Rename Existing “master” Branch to “main” Branch

The following command will rename your existing master branch into main.

git branch -m master main

Now check whether there is a branch called main by running the git branch command. It will list all the branches including the main branch.

git branch -a

Set the upstream of the main branch by running the following command. It will instruct Git to link the local main branch to the remote main branch. So when you use Git commands like fetch/push/pull in the future, this upstream reference will be used.

git push -u origin main

Finally, delete the master branch in the remote by running the following command.

git push origin --delete master

Sometimes, your Git hosting provider will not allow deleting the master branch. Under that kind of situation, login to your Git hosting account (Ex: Github.com) and change the default branch of your repository to main. After that, you will be able to delete the master branch without any problem.