Error Encyclopedia

Detached HEAD State

Fix detached HEAD state in Git. Learn what it means, how to avoid losing work, and how to reattach your HEAD to a branch.

What Does This Error Mean?

A 'detached HEAD' state means your Git HEAD is pointing directly to a commit rather than to a branch ref. You are no longer on any branch. Any new commits you make will be orphaned (not associated with any branch) and can be lost if you switch to another branch without preserving them.

Common Causes

1

Checking out a specific commit hash: git checkout abc123

2

Checking out a tag: git checkout v1.0.0

3

Running a rebase that pauses mid-operation

4

Checking out a remote tracking branch directly

5

Using git checkout HEAD~2 to navigate history

6

Bisecting with git bisect to find a bug

How to Fix It

Create a branch from the detached HEAD

If you have work in progress, create a branch to save it.

# Create a branch at the current position
git checkout -b my-temp-branch

# Or create branch first, then switch
git branch my-temp-branch
git checkout my-temp-branch

# Verify you are on the branch
git branch --show-current

Cherry-pick commits to a branch

If you made commits in detached HEAD, cherry-pick them to an existing branch.

# First, find the commit hashes
git log --oneline -5

# Switch to the branch you want to keep commits in
git checkout main

# Cherry-pick specific commits by hash
git cherry-pick abc123 def456

Stash and switch

If you have uncommitted changes, stash them before switching to a branch.

# Save uncommitted changes
git stash

# Switch to a branch
git checkout main

# Apply stashed changes
git stash pop

Checkout an existing branch

Simply switch to an existing branch to leave detached HEAD.

# List your branches
git branch

# Switch to a branch
git checkout main
git checkout develop

# Or use the shortcut
git switch -

Related Errors

Other common errors in this category:

Frequently Asked Questions

Will I lose my changes in detached HEAD?

Uncommitted changes can be lost if you switch branches without stashing. Committed changes can be recovered from git reflog for ~30 days, but they will be orphaned (not connected to any branch). Creating a branch preserves everything.

How do I recover lost commits from detached HEAD?

Use git reflog to find the commit hashes, then create a branch or cherry-pick. Run `git reflog` to see all HEAD movements with their commit hashes.