What is a detached HEAD, and how do you get out of it?
Detached HEAD means HEAD points directly at a commit instead of a branch, for example after checking out a tag or an old hash. New commits there belong to no branch and can be lost unless you create a branch.
Explain it simply
Imagine reading page 40 of a book with no bookmark. You can scribble notes, but once you close the book nobody knows where those notes were.
When you run git checkout a1b2c3d or check out a tag, HEAD is detached. Looking around is safe. If you commit, those commits hang off nothing, and after you switch away only the reflog remembers them, until garbage collection removes them.
To keep the work, create a branch while you are still there. To discard it, just switch back to a real branch.
Example
git checkout v1.0 # detached HEAD at the v1.0 tag
git commit -m "quick experiment"
git switch -c experiment # keep the work on a new branch
# or abandon it:
git switch main
# lost it already? find the hash:
git reflogWhat to say in the interview
"Detached HEAD means HEAD points at a commit, not a branch. It happens when I check out a tag or hash. Commits made there are not on any branch, so if I want to keep them I run git switch -c new-branch. If I only wanted to look, I switch back to main. git reflog can recover commits I forgot to save."
Common mistakes
- Committing in detached state and then switching away without making a branch.