Branches and merges

Inspect old commits and keep your work on a branch

Check out an earlier Git commit to investigate a bug, then save any new commits on a branch before switching back.

Checking an old commit helps you find when a bug appeared. Git lets you inspect that snapshot and make changes, but you need a branch to keep any new commits easy to find.

This lesson walks through inspecting a commit and saving your work. The Git detached HEAD guide explains the state behind it: 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