Git Detached HEAD State: Safe Recovery

Symptom

Git prints "You are in 'detached HEAD state'"; commits appear lost after switching branches.

Root cause

HEAD points at a commit instead of a branch — usually after checking out a tag, a remote branch, or a hash.

Fix, in order

1. Rescue any work you committed while detachedgit branch rescue-work # attaches HEAD history to a new branch
2. Return to your branchgit switch main
3. Merge or cherry-pick the rescue branchgit cherry-pick <sha>

Prevent it coming back

Never commit while detached unless you first create a branch.

Run it on clean infra

Spinning up a fresh box to reproduce or escape this error?

DevOps tools shelf

Related

Cloud & DevOps tool comparisons · Hardware build guides

NinjaOps publishes free engineering guides. Some outbound links are affiliate links: they cost you nothing and support the site.

Last reviewed 2026-10-02 · NinjaOps SEO grid · DevOps blog