
How to Change Default branch to 'main'
Table of Contents
Renaming the Local master as main
The initial action is to change the name of the “master” branch in your local GIT repositories as “main”:
$ git branch -m master main
Let’s quickly check if this has worked as expected:
$ git status
On branch main
Your branch is up to date with 'origin/master'.
nothing to commit, working tree clean
So far, so good! The local branch has been renamed - but we now need to make some changes on the remote repository as well!
Renaming the Remote master as main
In the second step, a new branch called “main” will need to be created on the remote repository. This is necessary because Git does not permit renaming of remote branches. The old “master” branch will then be removed after the new “main” branch has been created.
Make sure your current local HEAD branch is still “main” when executing the following command:
$ git push -u origin main
Deleting the Remote master Branch
We now have a new branch on the remote named “main”. Let’s go on and remove the old “master” branch on the remote:
$ git push origin --delete master
Depending on your exact setup, this might have worked and the renaming is successful. In many cases, however, you will see an error message like the following one:
To https://github.com/gittower/git-crashcourse.git
! [remote rejected] master (refusing to delete the current branch: refs/heads/master)
error: failed to push some refs to 'https://example@github.com/gittower/git-crashcourse.git'
GitHub, like other code-hosting platforms, expects you to define a “default” branch - and deleting this is not allowed. Additionally, your old “master” might be set as “protected”. You’ll need to resolve this before you can go on. In this case you can navigate to settings page in GIT web interface, locate the section for default branch, and change it from “master” to “main”.
Or if you don’t have access to make that change, you may need to reach out to the repository administrator to set the default branch via the repository settings in the web interface.
For reference, GitHub’s docs cover changing the default branch and renaming branches:
- https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-branches-in-your-repository/changing-the-default-branch
- https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-branches-in-your-repository/renaming-a-branch If you try again now, deleting “master” from the remote repository should be successful:
$ git push origin --delete master
To https://github.com/gittower/git-crashcourse.git
- [deleted] master
