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


    It can easily happen if you try to undo changes you've made by re-checking-out files and not quite getting the syntax right.

    You can look at the output of git log - you could paste the tail of the log here since the last successful commit, and we could all see what you did. Or you could paste-bin it and ask nicely in #git on freenode IRC.

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

    上一篇: Git更新子模块递归

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