Fix: Git Detached HEAD State — What It Means and How to Recover
Problem
You check out a specific commit or tag and Git warns you:
git checkout a3f2b1e
Git prints:
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.
You make a few commits and then realise they’re not on any branch. Now what?
Symptoms
git statusshowsHEAD detached at a3f2b1egit branchshows* (HEAD detached at a3f2b1e)instead of a branch name- New commits exist but aren’t linked to any branch ref
Root Cause
In Git, HEAD normally points to a branch reference (like refs/heads/main). When you git checkout a commit hash or tag directly, HEAD points to that specific commit — not a branch. This is a detached HEAD.
This is intentional behaviour. Git lets you explore any point in history. But commits made in this state have no branch pointer — they’re only reachable via the reflog. If you switch branches, those commits become dangling and can be garbage collected.
Solution
If you haven’t made any commits yet
Simply return to a branch:
git checkout main
Nothing is lost. You were just exploring.
If you’ve already made commits in detached HEAD
You have two options. First, note the current commit hash:
git log --oneline -1
# abc1234 (HEAD) Your experimental commit
Option 1: Create a branch at your current position (recommended)
git branch save-my-work
git checkout save-my-work
Now your commits live on a real branch.
Option 2: Switch to an existing branch and cherry-pick
# Find your detached commit hash first
git reflog
# abc1234 HEAD@{0}: commit: Your experimental commit
# Switch to your target branch
git checkout main
# Bring the commit over
git cherry-pick abc1234
When Detached HEAD is Useful
Detached HEAD isn’t a bug — it’s a feature:
- Exploring old commits:
git checkout v1.0.0to inspect a release tag - Running a build or test against a specific commit without branch pollution
- Bisecting:
git bisectintentionally uses detached HEAD to find bugs - Temporary experiments: Make commits you plan to throw away
Common Misconceptions
- “Detached HEAD means I lost data” — No. Commits still exist. They’re just not on a named branch.
- “I need to clone again” — Never needed. Everything is recoverable locally.
- “Detached HEAD is a Git bug” — It’s a deliberate feature for commit-level operations.
Verification
git branch
# * save-my-work
# main
git log --oneline -3
# Shows your commits on the new branch
Prevention
- Always work on a named branch for development:
git checkout -b feature/xyz - Check current state with
git statusbefore committing — it explicitly warns about detached HEAD - Set up a prompt that shows your Git branch/state (e.g.,
__git_ps1in bash) - Before
git checkout <hash>, ask yourself: “Do I need to commit here?” If so, create a branch first.