What does the detached HEAD state mean?
Detached HEAD is a state in Git where HEAD points directly to a specific commit instead of to a branch.
Simply put: you are "looking" at an old commit without being attached to a branch.
How HEAD normally works
In normal mode:
HEAD → main → the latest commit
You are on a branch, and new commits are added to its history without any issue.
What happens in detached HEAD
For example, you run:
git checkout a1b2c3dNow:
HEAD → commit a1b2c3d
- HEAD no longer points to a branch
- Git warns you that you are in a detached HEAD state
Why this is dangerous
In detached HEAD you can:
- read the code
- run the project
- experiment temporarily
But if you make a commit:
- it will not belong to any branch
- when you switch to another branch, this commit may get lost
How to work correctly in detached HEAD
If you realize you want to keep the changes:
git switch -c new-branchThis way you:
- create a new branch
- "attach" the commits to the history
When detached HEAD is normal
This is a normal state if you are:
- looking at an old version of the project
- checking a bug from the past
- running tests on a specific commit
- studying the history
How to exit detached HEAD
Just switch back to a branch:
git switch mainor
git checkout mainA frequent mistake in interviews
"Detached HEAD is an error" is wrong. It is a mode, not an error. The error is making commits and not saving them.
A short answer for an interview
Detached HEAD is a state where HEAD points directly to a commit rather than to a branch, so new commits are not preserved in the branch history unless a new branch is created.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.