Search code examples
gitbranchgit-commit

Not making an initial commit on master deletes master


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.


Solution

  • 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.