首页 > 解决方案 > git checkout remotes/origin/branch 和 git checkout branch 有什么区别?

问题描述

当我执行

git checkout remotes/origin/test_branch

我的 HEAD 处于分离状态。下面是输出:

C:\..\git_test>git checkout remotes/origin/test_branch
Note: checking out 'remotes/origin/test_branch'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b <new-branch-name>

HEAD is now at 4590fa2 Test branch commit
M       src/test/resources/**

C:\..\git_test>git branch -a
* (HEAD detached at origin/test_branch)
  test_branch
  master
  remotes/origin/HEAD -> origin/master
  remotes/origin/test_branch
  remotes/origin/master

如果我执行

git checkout test_branch

在同一个分支上,我不再处于分离状态。

C:\..\git_test>git checkout test_branch
Switched to branch 'test_branch'
M       src/test/resources/**
Your branch is up to date with 'origin/test_branch'.

C:\..\git_test>git branch -a
* test_branch
  master
  remotes/origin/HEAD -> origin/master
  remotes/origin/test_branch
  remotes/origin/master

请任何人都可以解释有什么区别以及为什么它会在分支相同的情况下进入分离状态?

标签: gitgit-checkoutgit-detached-head

解决方案


分支一样。

<branch>是您的本地版本。一个实际的分支。

remotes/origin/<branch>是一个远程跟踪分支。您无法直接控制这些,它们会自动更新fetch,它们是远程分支的图像,以便进行比较。

你不应该检查这些,因为承诺它们或移动它们的位置会破坏它们的目的。如果你确实尝试过(就像你做的那样),git 会做下一件最好的事情,它会检查这个引用指向的提交。导致分离的 HEAD 状态。


推荐阅读