Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Computer Basics / Git

    Branches and HEAD

    A branch is just a movable pointer to a commit — literally a tiny file containing a commit hash.

    Chapter 4 of 113 min read

    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.

    • HEAD is 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:

    Output
    $ 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 hash

    Under the Hood#

    Terminal
    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 ◀── HEAD

    Branches 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 questions
    1

    What is a branch, physically?

    Show answer

    A small file containing the hash of one commit — a movable pointer.

    2

    What is HEAD?

    Show answer

    A pointer to the branch (or commit) you're currently on.

    3

    When you commit, what moves?

    Show answer

    The current branch's pointer moves to the new commit (HEAD moves with it).

    4

    What is "detached HEAD"?

    Show answer

    HEAD pointing directly at a commit rather than at a branch; new commits there aren't on any branch.