Not making an initial commit on master deletes master

49 Views Asked by At

If I initialize a git repo in a folder, the default branch is master. This means a pointer is created which is named master but this pointer is not pointing to any commit yet. Now without making any commit first, if I create a new branch and switch to it, I cannot switch back to master. It gives this error: fatal: invalid reference: master. Why is the master branch(The pointer) deleted automatically? Does this mean that in git, the starting point of the entire repository needs to be a single commit and we cannot have multiple starting points, of course for separate branches.

2

There are 2 best solutions below

0
TTT On BEST ANSWER

Why is the master branch(The pointer) deleted automatically?

Actually it isn't deleted, because it doesn't exist. When you init a repo, the branch name that is displayed (e.g. main or master) is the name of the branch that's going to be created, once you create an initial commit. You can prove that there isn't a branch by init-ing a repo and then printing the branches (there will be none), or even trying to switch to the default branch name (you'll get an error):

/C/Git/TestRepo
$ git init
Initialized empty Git repository in C:/Git/TestRepo/.git/

/C/Git/TestRepo (main)
$ git branch

/C/Git/TestRepo (main)
$ git switch main
fatal: invalid reference: main

/C/Git/TestRepo (main)
$ git commit -m "Create an initial commit" --allow-empty
[main f76f8c5] Create an initial commit

/C/Git/TestRepo (main)
$ git branch
* main

/C/Git/TestRepo (main)
$ git switch main
Already on 'main'

Note in the above example I'm using Git Bash which has a two line prompt where the first line displays the current directory and the current branch name in parenthesis, e.g. (main), even when the branch doesn't actually exist.

0
Guildenstern On
$ git init
$ git checkout -b other
Switched to a new branch 'other'
$ git checkout -b master
Switched to a new branch 'master'
$ git checkout -b other
Switched to a new branch 'other'
$ git checkout -b master
Switched to a new branch 'master'

You can do this all day.

The initial branch has no commits so it is unborn; it’s not really created yet. When you then switch to another branch there is nothing to go back to.

But you can still switch to master. Create it again:

# with git-checkout(1)
git checkout -b master
# with git-switch(1) [1]
git switch -c master

Notes

  1. As of Git 2.43.0:

    THIS COMMAND IS EXPERIMENTAL. THE BEHAVIOR MAY CHANGE.