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

  1. Create a branch from detached HEAD to save work:
git checkout -b saved-work
  1. Or return to an existing branch (discarding detached work):
git checkout main
  1. 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 reflog to find them.
  • Pushing from detached HEAD is not possible without a branch.