exebook
exebook

Reputation: 33960

Why checkout -b does work only after second attempt?

$sudo git clone sample.git 

Cloning into 'sample'...
warning: You appear to have cloned an empty repository.
done.

$ cd sample

$ echo "hello world" > readme

$ git add readme

$ git checkout -b a
Switched to a new branch 'a'

$ git branch

$ git checkout master
error: pathspec 'master' did not match any file(s) known to git.

$ git checkout a
error: pathspec 'a' did not match any file(s) known to git.

$ git checkout -b b
Switched to a new branch 'b'

$ git branch

$ git commit -am .
[b (root-commit) 12b8434] .
 1 file changed, 1 insertion(+)
 create mode 100644 go

$ git branch
* b

$ git checkout a
error: pathspec 'a' did not match any file(s) known to git.

$ git checkout -b a
Switched to a new branch 'a'

$ git branch
* a
  b

What was wrong with my first checkout -b a, why the branch was not created?

Upvotes: 1

Views: 187

Answers (1)

AnoE
AnoE

Reputation: 8345

Well, you told git to create a branch in an empty repository. There is no commit yet, and a branch is just a "sticky note" pointing to a commit. So what is git supposed to do...

At least it stores your new branch in HEAD, so the branch tip will be updated with future commits. As shown by your commit.

More fun with empty repositories:

~/tmp> mkdir empty
~/tmp> cd empty
~/tmp/empty> git init
Initialized empty Git repository in tmp/empty/.git/
~/tmp/empty> git log
fatal: bad default revision 'HEAD'
~/tmp/empty> git branch xxx
fatal: Not a valid object name: 'master'.
~/tmp/empty> git checkout -b xxx
Switched to a new branch 'xxx'
~/tmp/empty> git log
fatal: bad default revision 'HEAD'
~/tmp/empty> ls -l .git/
branches/    config       description  HEAD         hooks/       info/        objects/     refs/
~/tmp/empty> cat .git/HEAD
ref: refs/heads/xxx
~/tmp/empty> ls -l .git/refs/heads
total 0

EDIT: adopted the comment from @jthill.

Upvotes: 6

Related Questions