Hone

Lessons · Git · committing with no branch attached

Looking around without a branch

A detached HEAD means HEAD points straight at a commit, not at a branch. Looking around is fine; new commits made there have no branch name and can be lost.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Checking out an old commit, a tag or a hash from a pull request all detach HEAD. Knowing the state explains the long warning Git prints and what to do if you want to keep work.

How to think about it

Read-only looking needs nothing. To keep commits made here, create a branch first (git switch -c name). To leave, switch to any branch.

Worked example

git switch --detach HEAD~1
Look at an old commit; HEAD points at a commit, not a branch.
git branch --show-current
Empty: no branch is checked out.
git switch -c from-old
To commit here safely, make a branch first.
git switch main
Back to the branch.

Your turn

Look at an old commit without a branch.

git switch  HEAD~3

The trap

Commits made on a detached HEAD are not lost at once. Git keeps a record of everywhere HEAD has been, called the reflog, and for a few weeks git reflog can still find them. But no branch name points at them, so treat them as lost unless you make a branch.

Practise committing with no branch attached on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.