git checkout my_branch vs. git checkout origin/my_branch

前端 未结 2 684
没有蜡笔的小新
没有蜡笔的小新 2021-02-03 22:41

I was on branch1 when I checkout branch2 like this (both branches are existing).

git checkout origin/branch2

then I got a

相关标签:
2条回答
  • 2021-02-03 22:59

    The "detached HEAD" message is a warning, not an error.

    The reason for it is simple enough. Git has two states you can be in with respect to branches:

    • on a branch, or
    • not on a branch.

    When you are on a branch and make new commits, the branch automatically advances to include the new commits.

    When you are not on a branch and make new commits, the non-branch also advances, but—here's the reason for the warning—if you then switch to some other branch (so that you are on it), git forgets where you were.1 When you are on a branch, the branch name remembers the new commits; when you are not, there is nothing to remember them.

    You can't be on a remote-tracking branch

    The branch origin/branch2 is a remote-tracking branch: that is, a branch that remembers "where branch2 was on origin the last time we (our git and origin's git) had a conversation about branches". Because the point of this is to track where they were, git won't let you get "on" that branch and make new commits (which would then remember where you are instead of where they were).

    Because you can't be on it, checking it out gives you that "detached HEAD" state instead.

    But you can be on a normal (local) branch

    The branch branch2 is a normal, ordinary, local branch. It is yours to do with as you wish. You can get on it and make new commits.

    (Your local branch can also remember the remote-tracking branch, as its so-called upstream. Git's confusing terminology for this is that your local branch is then "tracking" the remote-tracking branch. The word "tracking" appears too many times here, as does the word "branch", all with different meanings.)


    1Actually it saves it for a while, in the reflog for HEAD, but this is only good for 30 days by default.

    0 讨论(0)
  • 2021-02-03 23:04

    you should use git checkout --track origin/branch2 to create a local branch of branch2, which tracking the remote origin/branch2

    0 讨论(0)
提交回复
热议问题