World map

 

BM: Baca dalam Bahasa Melayu

World 2: Undo Magic

Detached HEAD

You will learn: how to visit an old commit and get back safely.

The problem

Four commits in the repository. The old one, Add day 1 page, glows and wobbles.

You want to see your diary as it was on day 1. Just look, not change. How?

Watch

HEAD leaves the main label and jumps back two commits, to Add day 1 page. main stays on Add day 2 entry.
6d3a9b1a8feb63270a76ebcf4670

git switch --detach HEAD~2 visits an old commit. HEAD now points at a commit, not a branch. This is a detached HEAD: HEAD points at a commit, not a branch. Good for looking around..

Try it

Visit the commit “Add day 1 page”.

6d3a9b1a8feb63270a76ebcf4670

Watch

git checkout HEAD~2 prints a long note about detached HEAD state, then: HEAD is now at Add day 1 page. Terminal output: $ git checkout HEAD~2 Note: switching to 'HEAD~2'. You are in 'detached HEAD' state. You can look around, make experimental changes and commit them, and you can discard any commits you make in this state without impacting any branches by switching back to a branch. If you want to create a new branch to retain commits you create, you may do so (now or later) by using -c with the switch command. Example: git switch -c <new-branch-name> Or undo this operation with: git switch - Turn off this advice by setting config variable advice.detachedHead to false HEAD is now at a8feb63 Add day 1 page

Old guides use git checkout with a commit. Same result, plus a long note. Don’t panic: it’s only advice.

Predict

You are on a detached HEAD. You commit, then switch to main. What happens to that commit?

Pick one answer.

Try it

You are visiting day 1. Get back to your branch.

6d3a9b1a8feb63270a76ebcf4670

You did it!

You can now visit old commits and come back safely.

Go deeper (optional)

git switch - jumps back to where you were before. Made commits while detached? Give them a branch before you leave, or they get left behind. Making branches comes in World 3. git checkout still works in Git 3.0, next to git switch.

git switch --detach HEAD~2 visits day 1. git switch - goes straight back to main. Terminal output: $ git switch --detach HEAD~2 HEAD is now at a8feb63 Add day 1 page $ git switch - Previous HEAD position was a8feb63 Add day 1 page Switched to branch 'main'