How to recover from detached HEAD in Git
· Category: Git
Short answer
Detached HEAD means you are not on any branch. Create a new branch to save your work, or checkout an existing branch to discard it.
Steps
- Create a branch from detached HEAD to save work:
git checkout -b saved-work
- Or return to an existing branch (discarding detached work):
git checkout main
- If you already made commits, recover them:
git reflog
Tips
- Detached HEAD is useful for inspecting old commits without affecting branches.
- Always create a branch if you intend to make changes while detached.
git switch -returns to the previous branch.
Common issues
- Losing commits made in detached HEAD: use
git reflogto find them. - Pushing from detached HEAD is not possible without a branch.