0

好的。这让我很困惑。我刚刚初始化了一个运行命令的空 git 存储库git init。然后我将一个文件添加到 git 的对象存储中,即git add .我试图创建一个分支,即git branch {branchname}. 我收到一个错误,因为根据我所阅读的内容,如果没有至少提交一次,我就无法创建分支。好的。我会咬。所以我再试试git checkout -b {branchname}。它似乎奏效了,即我被传送到我刚刚创建的分支。哇?我尝试git checkout master并得到错误error: pathspec 'master' did not match any file(s) known to git.

为什么我能够创建一个新分支而不签出master branch?我忽略了什么或没有理解什么?

4

2 回答 2

1

master, like originor upstream, 是约定,不是要求。由于您在 中没有提交master,因此您也没有任何参考。HEAD指向一个尚不存在的 ref。当你运行时git checkout -b branch,你要求 git:

  1. HEAD将您的点复制到 ref 。
  2. 将您HEAD指向新的参考。

由于您HEAD指向不存在的 ref,因此您没有复制任何内容,最终仍然没有指向任何内容。只要你在不提交的情况下继续切换分支,就会出现这种情况。

一旦你做了你的第一次提交,一切都会改变。既然您已经做出了提交,那么您就有了一个可供当前HEAD指向的参考。下次创建分支时,有一个要复制的 ref,因此下次切换时分支不会消失。

示例(ish):

git init
touch test
git add test
# There are no refs at this point, but HEAD is pointing to the nonexistent refs/heads/master
git checkout -b new_branch
git checkout master # fails, no refs (for master)
git checkout -b new_branch2
git checkout new_branch # fails, no refs (for new_branch)
git commit -m "Initial commit." 
# Now you have a ref for new_branch2, but not yet for any other branches.
git checkout -b new_branch3 # new_branch2's ref is duplicated
git checkout new_branch2 # success, you made a commit in this branch so it has a ref
git checkout new_branch3 # success, you made a commit in new_branch2 which this branch's ref is also pointing to.
git checkout master # failure, until you run with '-b' master doesn't have any refs yet.
于 2013-01-24T02:56:00.003 回答
0

它最初对我不起作用...

durrantm.../play$ mkdir ggg
durrantm.../play$ cd ggg
durrantm.../ggg$ git init
Initialized empty Git repository in /home/durrantm/play/ggg/.git/
durrantm.../ggg$ git checkout -b newy
fatal: You are on a branch yet to be born

...直到是的,我在 master 上做了一个初始提交:

durrantm.../ggg$ vi x.x
durrantm.../ggg$ git add .
durrantm.../ggg$ git commit -m"Initial Commit"
[master (root-commit) 75bcf19] Initial Commit
 0 files changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 x.x
durrantm.../ggg$ git checkout -b abc
Switched to a new branch 'abc'
durrantm.../ggg$ 
于 2013-01-24T01:17:34.950 回答