JuniorDebuggingOccasionalNot answered yet
What does "detached HEAD" mean in git and how do you recover from it?
A developer checks out a commit to inspect it, makes a commit, and then runs git status. Explain what state they are in and how to keep their work safe.
$ git checkout 9f3c1ab
Note: switching to '9f3c1ab'.
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 switching back to a branch.
HEAD is now at 9f3c1ab Fix off-by-one in parser
$ git commit -am "wip: new attempt"
[detached HEAD 4b21de0] wip: new attempt
Diagnose the cause.
Detached HEAD means HEAD points at a commit, not a branch — common after git checkout <sha>. Commits there are reachable only via reflog and can be GC'd. Save with git switch -c new-branch; return via git switch main. Harmless unless you commit and forget.
- ✗Committing in detached HEAD and switching away — commits lost (recovery via reflog)
- ✗Mistaking detached HEAD for a 'broken' state and resetting
- ✗Using
git checkoutfor both branch switching and inspection —git switch/git restore(C++17 of git 2.23+) clarifies intent
- →What is
git switch --detachand when do you use it intentionally? - →How do you find a 'lost' commit after leaving detached HEAD?