Why not git branch & lt; mybranch & gt; work but git checkout -b & lt; mybranch & gt; job?


As explained in this post git checkout -b <mybranch> runs two commands simultaneously

  1. git branch <mybranch>
  2. git checkout <mybranch>

I created a new git repository with git init. Now When I run git branch development I get the error:

Not a valid object name: 'development'.

If I run git checkout newbranch. I get the error:

pathspec 'newbranch2' did not match any file(s) known to git.

But if I use git checkout -b BigShotBranch then it simply creates that local branch with the message:

Switched to a new branch 'BigShotBranch'

so my question is why was the -b flag able to create the branch while any other method could not? Does the -b flag only combine two commands or do anything more than that?

P.S: This seems to be a glitch in git. After git checkout -b development the master branch is actually renamed to development. There is no master branch now.

A newly created empty repository is a corner case. Though .git/HEAD refers to refs/heads/master, actually .git/refs/heads/ is yet empty. "git branch newbranch" tries to resolve HEAD (in order to start the new branch from the current commit) and fails.

Even though "git checkout -b" is explained with the help of "git branch", underneath the former doesn't directly call the latter (but they obviously share some lower level code). Note that git checkout supports creating root branches via the --orphan switch, which git branch cannot. Evidently, in the empty repository situation git branch -b is actually run as git branch --orphan.