Git Detached HEAD: What It Is and How to Get Back Safely
⏱️ 2 min read
You are in 'detached HEAD' state means HEAD points at a commit hash instead of a branch. Git is fine; you're just standing somewhere with no name tag. The danger is only one: commits you make here belong to no branch, and when you switch away, they become unreachable except through reflog.
How you got here
git checkout <hash>, git checkout <tag>, or checking out a remote branch that doesn't exist locally yet (git checkout origin/feature instead of git switch feature). CI tools and tutorials that say "checkout the commit" also land people here by accident.
The three exits
Just leaving (no work done): git switch main (or checkout master). Nothing lost — the commit remains in the branch history.
Work you want to keep: git switch -c rescue-branch — this names the current position, and your commits become a normal branch you can push, PR or merge. Alternatively git branch rescue <hash> from anywhere if you already switched away.
Work you already abandoned: git reflog lists every HEAD movement (default 90 days). Find the orphaned commit's hash, then git branch recovered <hash>. This is the single most reassuring command in git — almost nothing is truly gone.
The habits that prevent it
Use git switch (branches) and git restore (files) instead of the overloaded checkout; git errors hard on detached-HEAD pushes to shared branches, which is a feature. And before force-switching away, git status — 5 seconds that saves reflog archaeology. Want a git sandbox where you can experiment without fear? Break things on a disposable VM — hourly servers cost cents.