Sub topic 12
Detached HEAD and how to leave it
This chapter assumes you can commit, create and switch branches, and read git log. You need Git 2.23 or later for git switch.
What detached HEAD means
Normally HEAD points to a branch name, and the branch points to a commit. When you commit, the branch moves forward and HEAD follows it.
In a detached HEAD state, HEAD points straight at a commit and no branch is involved. You get this state when you check out something that is not a local branch, such as a commit hash, a tag, or a remote-tracking branch like origin/main.
Entering the state
git log --oneline
git switch --detach a1b2c3d
git statusgit switch refuses to detach unless you pass --detach, so you rarely end up here by accident with it. git checkout a1b2c3d and git checkout v1.0 detach without asking, and Git prints a long warning. git status then shows HEAD detached at a1b2c3d.
Detached HEAD is safe for looking around. You can build, run tests, or inspect old code at that commit without touching any branch.
The danger: commits with no branch
You can commit while detached. Those commits are only reachable from HEAD. When you switch to a branch, nothing points at them anymore. Git will eventually delete unreachable commits during garbage collection, which by default happens after at least 30 days for reflog-protected commits.
Leaving the state
If you made no commits, or do not care about them, switch back to a branch:
git switch mainIf you made commits you want to keep, create a branch where you are, before switching away:
git switch -c fix/experimentThis turns the current position into a named branch, and HEAD attaches to it. You can then merge it like any other branch.
If you already switched away, find the commit hash in the output of git reflog and create a branch there:
git reflog
git branch recovered-work <commit-sha>Common errors
| Situation | What happens | Fix |
|---|---|---|
| `git checkout origin/main` then commit | Commits sit on no branch | `git switch -c new-branch` before leaving |
| Switching away right after committing | Warning about lost commits | Copy the hash, then `git branch name <hash>` |
| Using `git checkout <tag>` to "start work" | Detached at the tag | `git switch -c work-from-tag` |
| Confusing `git switch -` with recovery | It returns to the previous location, which may be detached | Use the reflog to find the commit |
Exercise
You checked out the tag v2.0, made two commits, then ran git switch main. Git warned that you left two commits behind. How do you get them back?
Show answer
Run git reflog to find the hash of the last commit you made while detached, then run git branch rescue <hash>. The branch rescue now points at your two commits. Alternatively, use the hash printed in Git's warning.