Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename main branch to master on a Github repository

Tags:

git

github

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 README.md
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 README.md 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 github.com

like image 954
handy Avatar asked Oct 24 '20 15:10

handy


People also ask

How do I change my main branch to master in GitHub?

If you go to the main repo page on GitHub and select the branches dropdown menu, you will see two branches listed and a checkmark next to master .

Can I rename my branch in GitHub?

Git Branch Rename Command The steps to change a git branch name are: Rename the Git branch locally with the git branch -m new-branch-name command. Push the new branch to your GitHub or GitLab repo. Delete the branch with the old name from your remote repo.


Video Answer


2 Answers

If README.md 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 README.md works the way you want, i.e. doesn't produce that error. Did you perhaps expect git init to create a default README.md?

like image 132
jthill Avatar answered Oct 21 '22 02:10

jthill


Using the -m option (move/rename) instead of -M with the name of the branch you're renaming from, here main, will work. Then you can push your renamed branch and maintain your reflog as well.

git branch -m main master
git push -u origin master

I also wrote a blog post with more details which can in case the repo was cloned by someone else before renaming the branch. You can check it out here.

like image 27
CodingNagger Avatar answered Oct 21 '22 02:10

CodingNagger