What does detached HEAD mean in Git and how do I get out of it?
Normally HEAD is a pointer to a branch name, and that branch points to a commit. Committing moves the branch forward and HEAD follows along. A detached HEAD means HEAD points straight at a commit with no branch in between, so there is nothing to move forward when you commit.
You end up detached by checking out something that is not a branch: a raw commit hash, a tag, or a remote-tracking reference. Some operations also detach temporarily as part of their normal work, including interactive rebase and bisect, which is why the state is not an error in itself.
Getting out depends entirely on whether you have made commits.
- If you have made no commits, nothing is at stake. Switch back to a branch and the detached state disappears. Git also offers a shortcut to return to whatever you had checked out previously.
- If you have made commits, create a branch before you leave. Those commits are reachable only by their hashes right now, and moving away leaves nothing pointing at them. Creating a branch at your current position preserves them, and you can then merge or rebase as usual.
The genuinely dangerous case is leaving a detached HEAD after committing without noticing. The work is not deleted immediately, but it is unreachable, and Git eventually garbage collects unreachable objects. Until that happens the reflog records every position HEAD has held, so you can find the lost commit there and create a branch pointing at it. This works reliably for recent work, which is why it is worth checking the reflog before concluding that anything is truly gone.
Git does warn you when detaching, and the warning includes the hash you would need. It is worth reading rather than scrolling past, because it is exactly the information required to recover.