2

Say I have a Git repo with three commits:

$ git log --oneline
62fa462 (HEAD, master) Third commit
76f2df9 Second commit
c05b82a First commit

Now I accidentally use checkout to move HEAD to the second commit:

$ git checkout 76f2df9
Previous HEAD position was 62fa462 Third commit
HEAD is now at 76f2df9 Second commit

I then want to restore the previous state so I use reset:

$ git reset --hard 62fa462
HEAD is now at 62fa462 Third commit

That worked, and as can be seen in the log, HEAD is again pointing to master:

$ git log --oneline
62fa462 (HEAD, master) Third commit
76f2df9 Second commit
c05b82a First commit

However, when I check the status, I get:

$ git status
HEAD detached from 76f2df9
nothing to commit, working tree clean

I don't really get this, why is HEAD still detached? In the log, it shows (HEAD, master) so it should point to the master branch, right? At least the log looks exactly like at the beginning when everything was fine.

What is going wrong here?

1 Answer 1

4

A detached HEAD means that HEAD is not a link to a branch head. A branch head is always a reference to a commit. HEAD, on the other hand, is a reference to either a commit or a branch head.

When you start, HEAD is specifically a reference to master, not 62fa462; graphically, it looks like

62fa462 <----- master <---- HEAD
   |
   v
76f2df9
   |
   v
c05b82a

After your checkout, HEAD no longer references a branch head, but a commit directly; that's what is meant by being detached.

$ git checkout 76f2df9


62fa462 <-+-- master
   |
   v
76f2df9 <----- HEAD
   |
   v
c05b82a

When you ran reset, you didn't check out the branch master; you checked out the commit that master referenced:

62fa462 <-+-- master
   |       \-- HEAD
   v
76f2df9
   |
   v
c05b82a

Only when you have a branch checked out can a branch head be advanced by a new commit; otherwise, only HEAD references the new commit, and you'll lose track of it the next time you run git checkout.

1
  • Ah, that makes a lot sense.
    – SampleTime
    Commented Sep 5, 2019 at 20:41

Not the answer you're looking for? Browse other questions tagged or ask your own question.