Git Detached HEAD — Commits Not on a Branch
Recover from a detached HEAD by attaching a new or existing branch before switching away, so commits are not left unreachable.
Symptoms
- git status reports 'HEAD detached at <sha>' or 'You are in detached HEAD state'
- git branch --show-current prints nothing
- Commits made in this state disappear after checking out another branch
Possible causes
- git checkout <commit>, <tag>, or a remote branch without creating a local branch
- A rebase or bisect is in progress
- CI or a script checks out a specific commit and then commits changes
Diagnosis steps
Confirm the state and current commit
git status && git log --oneline -1Interpretation
A detached HEAD points directly at a commit. Any new commit is not attached to a branch until you create one.
Check whether you have made commits since detaching
git reflog --date=iso | head -10Interpretation
Reflog entries show recent commits. If you committed while detached, note the SHA before switching away.
Root cause
HEAD points to a commit rather than a branch reference. Git can still create commits, but nothing names them, so switching branches leaves them reachable only through the reflog until garbage collection.
Fix
If you have no local changes, switch back to a branch. If you made commits, create a branch at the current commit before switching, then merge or cherry-pick it into the intended branch. In CI, check out a branch or create one explicitly when pushing.
Risk note
Switching away from a detached HEAD without creating a branch can make new commits hard to find. Reflog recovery is possible but expires.
Verify the fix
Run git branch --show-current and confirm it prints a branch name. Verify the new commits are reachable with git log on that branch, then push the branch so the work is durable.
What detached HEAD means
Normally HEAD points to a branch, and the branch points to a commit. In a detached HEAD, HEAD points directly to a commit. You can inspect and even commit, but those commits have no branch name until you create one.
git status
git branch --show-current # empty when detached
Recover
No new commits:
git switch -
New commits made while detached:
git switch -c rescue-work
git switch main
git merge rescue-work # or cherry-pick specific commits
Verify
git branch --show-currentprints a branch.git log --onelineon the branch includes the recovered commits.- The branch is pushed to the remote.
git statusno longer says detached HEAD.
Prevention
Use git switch <branch> for branches and git switch --detach <sha> when you intentionally want a detached state. Before leaving a detached HEAD, check git status and create a branch if you committed. CI workflows that commit should create or check out a branch explicitly.