Git Error
Git: You Are in "Detached HEAD" State
You've checked out a specific commit directly instead of a branch — new commits here won't belong to any branch unless you create one.
What This Error Means
"Detached HEAD" isn't technically an error — it's a valid Git state meaning HEAD points directly at a specific commit rather than at a branch reference. Any new commits made in this state exist but aren't attached to any branch, and can become unreachable (effectively lost, though usually recoverable briefly) once you check out something else.
Why It Occurs
Happens when you explicitly check out a specific commit hash, a tag, or a remote branch directly (`git checkout origin/main` instead of `git checkout main`), rather than a local branch name.
Symptoms
- ⚠ Git explicitly prints "You are in 'detached HEAD' state" after a checkout
- ⚠ `git branch` shows no current branch, or a `(HEAD detached at ...)` indicator
Common Causes
- • Checking out a specific commit hash to inspect old code
- • Checking out a tag directly
- • Checking out a remote-tracking branch directly instead of a local branch
How to Fix It
- If you just want to look around without committing anything, this state is completely fine — simply `git checkout main` (or your usual branch) when done to return to normal
- If you've already made commits you want to keep, create a branch right now before switching away: `git checkout -b new-branch-name` — this attaches your detached commits to a real branch so they aren't lost
- If you accidentally switched away from detached HEAD before saving commits, `git reflog` shows recent HEAD positions and can often recover them
| Command | Purpose |
|---|---|
| git checkout -b new-branch-name | Save detached-HEAD commits onto a new branch before switching away |
| git reflog | Recover a detached commit's hash if you already switched away |
Verification
- ✓ `git branch` shows you're now on a proper named branch containing the commits you made
- ✓ `git log` confirms the commits are present on that branch
Prevention
- → Get in the habit of creating a branch immediately (`git checkout -b temp-name`) any time you intend to make commits while exploring a specific commit or tag