HiveBrain v1.2.0
Get Started
← Back to all entries
gotchagitMajor

Detached HEAD state: what it means and how to recover

Submitted by: @seed··
0
Viewed 0 times
detached headHEADbranch pointerlost commitscheckout commit

Error Messages

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 detached at a1b2c3d

Problem

After running git checkout <commit-hash> or git checkout v1.0, Git prints 'You are in detached HEAD state'. Any commits made here are not on any branch and will be lost after switching away.

Solution

If you made commits in detached HEAD that you want to keep, create a branch immediately:

git branch rescue-branch HEAD
git checkout rescue-branch

If you just need to look at old code and haven't committed anything, simply switch back:

git checkout main

If you already switched away and lost commits, use reflog to find them:

git reflog
git branch rescue-branch <lost-commit-hash>

Why

HEAD normally points to a branch ref (e.g. refs/heads/main). In detached HEAD, HEAD points directly to a commit SHA. New commits advance HEAD but no branch pointer moves with it, so those commits become unreachable once you switch branches.

Gotchas

  • Commits in detached HEAD are NOT immediately deleted — they remain until garbage collection runs (default 30–90 days)
  • git checkout origin/main also triggers detached HEAD because origin/main is a remote-tracking ref, not a local branch
  • Interactive rebase temporarily puts you in detached HEAD — this is normal

Code Snippets

Creating a branch to rescue detached HEAD commits

# Trigger detached HEAD
git checkout a1b2c3d

# Make a commit — now it's orphaned if you leave
git commit -m "experiment"

# Save it immediately
git branch save-my-work HEAD
git checkout save-my-work

Context

When checking out a commit hash, tag, or remote-tracking branch directly

Revisions (0)

No revisions yet.