Tour of Git
Branching & Merging / Lesson 2.7

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:

  1. Create a file and commit: echo "first" > file.txt then git add file.txt then git commit -m "First commit"
  2. Make a second commit: echo "second" >> file.txt then git add file.txt then git commit -m "Second commit"
  3. Find the first commit hash: git log --oneline
  4. Checkout that commit: git checkout <first-commit-hash> — you are now in detached HEAD
  5. Verify: git status shows "HEAD detached at ..."
  6. Make a commit here: echo "detached work" >> file.txt then git add file.txt then git commit -m "Work in detached HEAD"
  7. Save your work by creating a branch: git checkout -b rescue-branch
  8. Verify the branch exists: git branch — you should see rescue-branch with your commit
  9. 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.

🎯

Goal

Enter detached HEAD state, create a commit, then save it by creating a new branch

Terminal
$

No commits yet. Run `git init` and create your first commit.