为什么checkout -b只在第二次尝试后才能工作?

时间:2016-07-11 12:52:04

标签: git

$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

我的第一个checkout -b a出了什么问题,为什么没有创建分支?

1 个答案:

答案 0 :(得分:6)

嗯,你告诉git在空的存储库中创建一个分支。还没有提交,分支只是一个"粘滞便笺"指向提交。那么git应该做什么......

至少它会将您的新分支存储在HEAD中,因此分支提示将在未来的提交中更新。如你的提交所示。

使用空存储库更有趣:

~/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

编辑:采纳了@jthill的评论。