W3docs

Detached HEAD

Understand the Git detached HEAD state — what it means, why it happens, how to keep work you do in it, and how to get back to a branch.

Definition

A detached HEAD is when HEAD points directly at a commit instead of at a branch. Normally HEAD references a branch name (like main), and that branch points to the latest commit — so committing moves the branch forward with you. In a detached HEAD state, that chain is broken: HEAD sits on a specific commit with no branch to carry your new commits along.

HEAD pointing through a branch versus HEAD pointing directly at a commit

How HEAD normally works

In the usual "attached" state, the references form a chain: HEAD → branch → commit. When you make a new commit, Git advances the branch pointer to the new commit, and because HEAD points to the branch, it follows automatically. Your history stays anchored to a named branch.

What detaches HEAD

HEAD detaches whenever you check out something that is not a branch — most often a specific commit, a tag, or a remote-tracking reference:

git checkout a1b2c3d      # a commit hash
git checkout v1.0.0       # a tag
git switch --detach main  # explicitly detach

Git warns you when this happens and tells you that you are in a "detached HEAD" state.

Why it matters

Looking around in a detached HEAD is perfectly safe — it is great for inspecting or building an old commit. The danger appears when you commit there. Because no branch is tracking your work, those new commits are only reachable through HEAD. The moment you switch to another branch, they become "dangling": still in the repository for a while, but with nothing pointing at them, and eventually garbage-collected.

Keeping work you did in a detached HEAD

If you made commits in a detached HEAD and want to keep them, create a branch before moving away. This anchors the commits to a name:

git switch -c my-rescued-work

Your detached commits now live on the new branch, safe and reachable.

Getting back to normal

To leave a detached HEAD without keeping any new commits, just switch to a branch:

git switch main

If you committed in the detached state, forgot to branch, and have already switched away, do not panic — git reflog records where HEAD has been. Find the lost commit's hash there and recover it:

git reflog
git switch -c recovered <lost-commit-hash>

Practice

Practice

Which statements about a detached HEAD are correct?