Why did my Git repo enter a detached HEAD state?

I ended up with a detached head today, the same problem as described in: git push says everything up-to-date even though I have local changes

As far as I know I didn't do anything out of the ordinary, just commits and pushes from my local repo.

So how did I end up with a detached HEAD ?


Any checkout of a commit that is not the name of one of your branches will get you a detached HEAD. A SHA1 which represents the tip of a branch would still gives a detached HEAD. Only a checkout of a local branch name avoids that mode.

See committing with a detached HEAD

When HEAD is detached, commits work like normal, except no named branch gets updated. (You can think of this as an anonymous branch.)

替代文字

For example, if you checkout a "remote branch" without tracking it first, you can end up with a detached HEAD.

See git: switch branch without detaching head


I reproduced this just now by accident:

  • lists the remote branches

    git branch -r
          origin/Feature/f1234
          origin/master
    
  • I want to checkout one locally, so I cut paste:

    git checkout origin/Feature/f1234
    
  • Presto! Detached HEAD state

    You are in 'detached HEAD' state. [...])
    

  • Solution #1:

    Do not include origin/ at the front of my branch spec when checking it out:

    git checkout Feature/f1234
    

    Solution #2:

    Add -b parameter which creates a local branch from the remote

    git checkout -b origin/Feature/f1234 or

    git checkout -b Feature/f1234 it will fall back to origin automatically


    try

    git reflog 
    

    this gives you a history of how your HEAD and branch pointers where moved in the past.

    eg :

    88ea06b HEAD@{0}: checkout: moving from DEVELOPMENT to remotes/origin/SomeNiceFeature e47bf80 HEAD@{1}: pull origin DEVELOPMENT: Fast-forward

    the top of this list is one reasone one might encounter a DETACHED HEAD state ... checking out a remote tracking branch.

    链接地址: http://www.djcxy.com/p/45050.html

    上一篇: Git rebase失去了历史,那么为什么要rebase?

    下一篇: 为什么我的Git仓库进入独立HEAD状态?