On This Page
What is a Detached HEAD in Git and How to Fix It
Quick Answer: A detached HEAD means Git’s HEAD pointer is pointing directly to a specific commit hash rather than a named branch pointer (like main or dev). Any new commits made in detached HEAD state are not attached to any branch and will be lost when you switch away unless you create a branch to save them (git switch -c <new-branch-name>).
Why Did My Repository Enter Detached HEAD?
Normally, .git/HEAD holds a reference to a branch file (e.g. ref: refs/heads/main). When you commit, the branch file updates to the new commit hash, and HEAD follows the branch.
You enter a detached HEAD state when you run git checkout directly on a commit hash or tag instead of a branch name:
$ git checkout a1b2c3d
# Output: You are in 'detached HEAD' state. You can look around, make experimental changes...
Here, .git/HEAD contains the literal string a1b2c3d... rather than a branch path.
How to Fix Detached HEAD
Case A: You Want to Save Commits Made in Detached HEAD
If you made new commits while in detached HEAD state and want to keep them, create a new branch right where you are:
# 1. Create a new branch pointing at your current commit
$ git switch -c my-saved-work
# (or: git checkout -b my-saved-work)
# 2. Merge your new branch back into main if desired
$ git checkout main
$ git merge my-saved-work
Case B: You Made No Commits (or Want to Discard Experimental Edits)
If you were just inspecting old code and made no changes you want to keep, simply check out your branch again:
$ git checkout main
Your repository returns to normal, pointing HEAD back to refs/heads/main.
What Happens to Orphaned Commits?
If you switch away from a detached HEAD state without creating a branch, the commits you made become orphaned (unreferenced). They will not show up in normal git log output and will eventually be cleaned up by Git’s garbage collection (git gc).
If you accidentally switched away and lost a commit, recover it using git reflog:
$ git reflog
# Find the hash of your commit in the reflog list
$ git branch recovered-work <commit-hash>
For more details on reference files and pointer structures, see /git-refs and /git-checkout.