Branches and merges
Git, detached HEAD
Understand the Git detached HEAD state, when HEAD points to a commit instead of a branch, and how to create a branch so you do not lose new commits.
Your Git repository can end up in a state called detached HEAD.
The name sounds scary. It is not damage. It just means HEAD points directly at a commit instead of at a branch name.
Normally HEAD points to a branch, and that branch points to the latest commit. When you commit, Git moves the branch forward. That is an attached HEAD.
In a detached HEAD state, HEAD points at a commit with no branch name behind it. Git still lets you look around and make commits. The danger is losing those commits when you switch away.
How you get there
This often happens during debugging. You want to find the commit that introduced a bug, so you check out individual commits until the code works again:
git checkout a1b2c3d
Or with the newer command:
git switch --detach a1b2c3d
When you are done inspecting, return to a branch:
git checkout main
Do not lose new commits
The risky case is different. You are in detached HEAD, you make one or more new commits, and then you switch to another branch without saving them.
Those commits still exist in the object database for a while, but no branch points to them. They become hard to find.
Create a branch at the current commit before you switch away:
git branch rescue-work
git checkout rescue-work
Or in one step:
git checkout -b rescue-work
Now the commits belong to a named branch and will not disappear when you move on.
If your situation is messier than this, I built a free Git recovery tool: describe the mess, and it gives you the recovery steps. There is also a longer write-up at /git/.
Lesson completed