The Plain Picture#
A bookmark in the photo album. The bookmark "main" sits on the latest photo of the official version. You add a second bookmark, "bonus", to try an idea. When you take a new photo while using "bonus", that bookmark moves forward to it; "main" stays put. And there's a little "you are here" arrow showing which bookmark you're currently using.
The Real Names#
A branch is just a movable pointer to a commit — literally a tiny file containing a commit hash.
HEADis the "you are here" arrow: it points to the branch you're on (and so, indirectly, to its commit).When you commit, the branch HEAD points to moves forward to the new commit.
Real proof from the practice repo:
$ cat .git/HEAD
ref: refs/heads/main ← HEAD points to the branch "main"
$ cat .git/refs/heads/main
80b9b6d980cd3f672518a042340c567460d3dd30 ← "main" is just a file holding a commit hashUnder the Hood#
git switch -c bonus # create branch "bonus" here and switch to it (older command: git checkout -b bonus)
git branch # list branches; * marks the current one
git switch main # go back to main after creating "bonus": after committing "Add bonus points" on bonus:
main main
│ │
[7ef9500] ◀─────┘ [7ef9500] ◀──────┘
▲ ▲
└───── bonus ◀── HEAD └──── [9ffbfe2] ◀── bonus ◀── HEADBranches are almost free — creating one writes a 41-byte file. So the normal practice is: a new branch for every piece of work, however small.
Detached HEAD: if you switch to a commit instead of a branch (git switch --detach 7ef9500, handy to look at old
code), HEAD points straight at a commit. Commits made there belong to no branch and are easy to lose — create a branch
(git switch -c rescue) if you want to keep them.
Check yourself
4 questionsWhat is a branch, physically?
Show answerHide answer
A small file containing the hash of one commit — a movable pointer.
What is HEAD?
Show answerHide answer
A pointer to the branch (or commit) you're currently on.
When you commit, what moves?
Show answerHide answer
The current branch's pointer moves to the new commit (HEAD moves with it).
What is "detached HEAD"?
Show answerHide answer
HEAD pointing directly at a commit rather than at a branch; new commits there aren't on any branch.