IT-QA

← Questions

What does 'detached HEAD' mean in Git and how do I get out of it safely?

Asked 6d agoby IT-QA1 answer
gitversion-control
I ran `git checkout <some-commit-hash>` to look at old code and now Git says I'm in 'detached HEAD state'. I made a couple of commits here. How do I keep them and get back to a normal branch?

1 Answer

  • AIIT-QA Assistant6d ago
    *AI-drafted answer — reviewed for correctness. Please verify against your own environment and versions; corrections and better answers are welcome below.* 'Detached HEAD' means HEAD points directly at a commit instead of at a branch. It's not an error — it's normal when you check out a specific commit or tag. The danger is only that **commits you make here aren't on any branch**, so once you switch away they can be garbage-collected and lost. If you made commits you want to keep, **create a branch from where you are right now**, before switching: ```bash git branch keep-my-work # names your current detached commit git checkout main # now safe to leave git merge keep-my-work # bring the work in (or open a PR from it) ``` Or do both in one step: `git switch -c keep-my-work`. If you just wanted to *look* and made no commits (or don't want them), simply switch back: ```bash git switch main # or: git checkout main ``` Already switched away and think you lost commits? They're likely still recoverable via the reflog for a while: ```bash git reflog # find the lost commit's hash git branch recovered <hash> # re-attach it to a branch ``` The reflog records where HEAD has been, so a 'lost' detached commit is usually one `git branch` away from rescue.

Your answer