How to rename main branch to master on a Github repository


I’d like to create a github repository and rename the main branch to master.

If I create a new repository on github and do

git init
git add
git commit -m "first commit"
git branch -M master

I get

error: refname refs/heads/master not found
fatal: Branch rename failed

so I seem to somehow not understand git well enough. What’s the issue here?

I must have gotten confused when I was playing around with the above. The following happens:

git init create the repository

git add adds the file

git commit -m "first commit" adds the file to the master branch since that still default for git

so I never have to rename it in the first place. Now Github uses the default main, which can be changed in settings -> repositories on


If doesn’t actually exist, git checkout -B master will do what you want. git branch -M is expecting a full ref that actually refers to something, not the stub git init (or git checkout --orphan) creates. I’d agree it "should" handle this case, whether it’s worth a patch is up to anybody capable of writing a good one. Shouldn’t be too hard.

My test case that led to this answer was simply running your commands in an empty directory; that produced your reported symptom. Running them in a directory that (already) includes a works the way you want, i.e. doesn’t produce that error. Did you perhaps expect git init to create a default

Answered By – jthill

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published