Detached HEAD — Understanding and Recovering
A detached HEAD means your HEAD pointer is not on a branch — it points directly at a specific commit. This is not an error, but any commits you make can be lost if you switch away without saving them to a branch.
What Does HEAD Normally Look Like?
HEAD ──→ main ──→ commit C
HEAD points to a branch, and the branch points to a commit. When you make a new commit, the branch moves forward and HEAD follows.
What Is Detached HEAD?
HEAD ──→ commit B (no branch!)
main ──→ commit C
HEAD points directly at a commit, skipping any branch. This happens when you checkout a specific commit, a tag, or a remote branch.
How Do You Get Into Detached HEAD?
git checkout abc1234 # checkout a specific commit hash
git checkout v1.0 # checkout a tag
git checkout origin/main # checkout a remote-tracking branch
Git will warn you:
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...
The Danger
If you make commits in detached HEAD and then switch branches, those commits become orphaned — no branch points to them. Git's garbage collector will eventually delete them.
HEAD ──→ commit X ──→ commit Y (orphaned!)
main ──→ commit C
How to Recover
Create a branch from the detached HEAD to save your work:
git branch my-rescue-branch
git checkout my-rescue-branch
Or in one step:
git checkout -b my-rescue-branch
If you already switched away and lost the commit, use git reflog to find it:
git reflog
# find the commit hash
git checkout -b rescue abc1234
Try it!
Practice entering and recovering from detached HEAD:
- Create a file and commit:
echo "first" > file.txtthengit add file.txtthengit commit -m "First commit" - Make a second commit:
echo "second" >> file.txtthengit add file.txtthengit commit -m "Second commit" - Find the first commit hash:
git log --oneline - Checkout that commit:
git checkout <first-commit-hash>— you are now in detached HEAD - Verify:
git statusshows "HEAD detached at ..." - Make a commit here:
echo "detached work" >> file.txtthengit add file.txtthengit commit -m "Work in detached HEAD" - Save your work by creating a branch:
git checkout -b rescue-branch - Verify the branch exists:
git branch— you should seerescue-branchwith your commit - Switch back to main:
git checkout main
Key Insight
Detached HEAD is not scary once you understand it. It simply means "you're not on a branch." The fix is always the same: create a branch to save your work before switching away.