Introduction
Branches sound heavy, but in Git they are the lightest thing there is: a branch is a name that points to one commit, stored in a file 41 bytes long. Creating a branch is instant, and dozens of branches cost nothing. Understanding refs and HEAD explains what git switch does, why "detached HEAD" warnings appear, and how commands accept names like HEAD~3.
How it works
A ref is a name for a commit id. Branches live under .git/refs/heads/: the file .git/refs/heads/main contains the id of the commit at the tip of main. When you commit on a branch, Git creates the commit with the old tip as parent and moves the branch to the new commit.
HEAD says what is checked out. Normally it is a symbolic ref: the file .git/HEAD contains ref: refs/heads/main, meaning "the current branch is main". If you check out a commit directly, HEAD contains the commit id itself: a detached HEAD. New commits made there belong to no branch and are easy to lose, so create a branch first if you want to keep them.
A commit is contained in a branch if it can be reached from the branch's tip by following parent links. git branch --contains abc1234 lists those branches.
Commands accept revision expressions:
- a branch name,
HEAD, a tag, or an abbreviated id; X~n: go back n commits following first parents (X~meansX~1);X^n: the n-th parent of a merge commit X (X^meansX^1,X^0means X itself);- suffixes combine from left to right:
HEAD^2~1is the first parent of HEAD's second parent.
git branch # list branches; * marks the current one
git switch -c feature # create a branch at HEAD and switch to it
git log --oneline main~3 # history starting three commits before main
git switch --detach v1.0 # look at an old version without a branch
cat .git/HEAD # ref: refs/heads/feature
Example
commits = {
"a1": [],
"b2": ["a1"],
"c3": ["b2"],
"f1": ["b2"],
"m4": ["c3", "f1"],
}
refs = {"main": "m4", "feature": "f1"}
head = "ref: main"
def resolve(name):
if name == "HEAD":
return refs[head[5:]] if head.startswith("ref: ") else head
return refs.get(name, name)
def parse(expression):
name, suffixes = expression, ""
for i, ch in enumerate(expression):
if ch in "~^":
name, suffixes = expression[:i], expression[i:]
break
oid = resolve(name)
i = 0
while i < len(suffixes):
op = suffixes[i]
i += 1
digits = ""
while i < len(suffixes) and suffixes[i].isdigit():
digits += suffixes[i]
i += 1
n = int(digits) if digits else 1
if op == "~":
for _ in range(n):
oid = commits[oid][0]
else:
oid = commits[oid][n - 1]
return oid
print("HEAD is", head, "->", resolve("HEAD"))
for expression in ["HEAD~1", "HEAD^2", "HEAD~2", "main~3", "feature^", "HEAD^2~1"]:
print(f"{expression:9} -> {parse(expression)}")
head = "c3"
print("after checking out a commit directly, HEAD is detached:", resolve("HEAD"))Line by line
- The history has a merge commit
m4whose first parent isc3(main's line) and second parentf1(the feature). refsmaps branch names to commits, and HEAD points tomain.HEAD~1follows the first parent toc3, whileHEAD^2takes the second parent,f1.HEAD^2~1combines both: the second parent, then its first parent,b2.- Setting HEAD to a commit id detaches it: it no longer names a branch.
Expected result
HEAD is ref: main -> m4
HEAD~1 -> c3
HEAD^2 -> f1
HEAD~2 -> b2
main~3 -> a1
feature^ -> b2
HEAD^2~1 -> b2
after checking out a commit directly, HEAD is detached: c3
In the real world
CI systems check out commits in detached-HEAD state all the time, because they build exact commits rather than moving branches. Release scripts compare HEAD with tags such as v2.1.0, and git bisect moves a detached HEAD around the history to find the commit that introduced a bug. Hosting services protect important refs such as main from being moved by force.
Common mistakes
- Committing on a detached HEAD and switching away, leaving the commits on no branch.
- Confusing ~ and ^:
HEAD~2is the grandparent;HEAD^2is the second parent of a merge. - Thinking deleting a branch deletes its commits: it only removes the name, though unreachable commits are eventually cleaned up.
- Using too short an abbreviation, which Git rejects as ambiguous.
Best practices
- Create a branch (
git switch -c name) before committing on a detached HEAD. - Use
git log --oneline --graph --allto see where every branch points. - Name branches by purpose, such as
fix-login-timeout.
Summary
A branch is a ref, a name holding a commit id, that moves when you commit on it. HEAD normally points to the current branch and is detached when it holds a commit id directly. Revision expressions name commits relative to others: ~n walks first parents and ^n picks a merge's n-th parent.
Quick check
Key takeaways
- A branch is a file containing a commit id; committing moves the current branch to the new commit.
- HEAD normally contains "ref: refs/heads/main"; when it holds a commit id directly, it is detached.
- ~n follows first parents n times; ^n chooses the n-th parent of a merge.
Practice problems for this lesson
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.