Git Parent Traversal: Caret and Tilde
Read the graph, not the clock
Our fixture has A as root, B as its child, C as the main-side child of B, D as the topic-side child of B, E as the child of D, and M with ordered parents C and E. HEAD points to main at M. This directed acyclic graph (DAG) is defined by parent links, not by commit dates or the horizontal position of nodes in a graph drawing.
git log --graph --oneline --allgit rev-list --parents -n 1 MTwo different operations
Caret followed by a positive integer chooses that numbered parent in one step; tilde followed by a number walks that many first-parent steps. For M, HEAD^ and HEAD^1 give C, HEAD^2 gives E, HEAD2 gives B, HEAD3 gives A. HEAD^21 gives D: first select E, then its first parent. HEAD0 keeps M; ^0 resolves a commit rather than selecting parent zero.
git rev-parse HEAD^2 Egit rev-parse HEAD~2 Bgit rev-parse HEAD^2~1 DAvoid invalid traversal
A root has no parent, and a one-parent commit has no second parent. A^ and C^2 fail in the fixture. The graph may contain merges with more than two parents; inspect actual ordering, do not infer it from branch names. Some shells interpret special characters; quote revision expressions where necessary. Bash is used here.
git rev-parse --verify --quiet "C^2"printf "exit=%s\n" "$?"Practice: trace a mixed expression
Predict HEAD^2^1^1 before running rev-parse: M to E, E to D, D to B. Check its ID against B. In a log, --first-parent M follows the main-side path M, C, B, A; that view intentionally omits D and E. Next lesson uses the whole reachable set.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Git Parent Traversal: Caret and Tilde — knowledge check
Predict revision resolution, commit sets and path selection.
What does HEAD^2 select in the fixture?
What does HEAD~2 select?
What does HEAD^2~1 select?
What happens when resolving C^2?
What does --first-parent M omit from the walk?