首页 > 解决方案 > 为什么每次我创建一个新分支时我的本地 git 分支都会消失?

问题描述

我有几个月没有使用 Git。我刚开始一个新项目,有件事让我很困扰:每次我创建一个新分支时,已经存在的分支就会消失,就好像它被替换了一样。我的意思是,当我做“git branch”时,我什么都没有!显然,我的“git checkout”不起作用。我什至没有我的分支了。只有当前的一个。

我已经在工作的项目没有这个问题。

这是为什么?

标签: gitbranchgit-branch

解决方案


这很正常:您刚刚创建了一个新项目:

$ mkdir newproj
$ cd newproj
$ git init
Initialized empty Git repository in .../newproj

此时,不存在分支。尽管如此,正如git status将告诉您的那样,您在master分支上:

$ git branch
$ git status
On branch master

No commits yet

nothing to commit (create/copy files and use "git add" to track)
$ 

您可以使用以下命令切换到另一个分支git checkout -b

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

现在你仍然没有分支,但现在你在分支上xyz,正如git status将告诉你的那样。

这种奇怪的状态是正常的,因为没有提交。当没有提交时,就没有分支,因为分支名称只包含一些现有提交的哈希 ID。没有提交,就不能存在分支名称。

当你创建一个的提交时,Git 会执行以下步骤(前几个没有任何特定的顺序;只有最后几个有实际顺序):

  1. 收集您的姓名和电子邮件地址,以在新提交中使用。
  2. 获取(您的计算机的想法)当前时间,附加到您的姓名和电子邮件地址。
  3. 收集日志消息。
  4. Freeze the contents of the index (the index being where you build new commits: git add copies files from the work-tree into the index).
  5. Get the hash ID of the current commit, if there is a current commit. Get the hash ID of any commits being merged as well, if that's going on.
  6. Use all of this information to create a new commit. Creating the commit assigns it its hash ID, which is a cryptographic checksum of all of these contents (your name and email address with the time stamp, your log message, the hash ID of the frozen tree, and so on).
  7. Write the hash ID obtained by writing the new commit. This new commit's hash ID goes into the current branch name. If the branch name did not exist before this point, well, now it exists.

Hence, it's not until you make at least one commit that you can have any branch names. But you can still choose which branch name is your current branch, even if that branch can't exist: it's the creation of the first commit that will create the branch name.

(Once you do have at least one commit, you can attach as many names as you like to the one commit. If you have more than one commit, you can attach as many names as you like to every commit, though most commits don't need any names attached to them. Git finds them by working backwards from a later commit. Only the last commit—the tip of a branch—ever needs a name, so that Git can find it without first finding a later commit.)


推荐阅读