Understand HEAD^ and HEAD~ in Git

Use caret notation to choose a parent and tilde notation to follow the first-parent chain, including merge histories and revision ranges.

Best practices
Illustration of Git branches and version history

HEAD^ selects the first parent of HEAD; HEAD~1 follows one first-parent step and therefore selects the same commit. The difference appears when a number follows the operator: HEAD^2 selects the second parent, while HEAD~2 follows the first parent twice.

Read the parent notation

Expression Meaning
HEAD^ or HEAD^1 First parent
HEAD^2 Second parent, if present
HEAD^3 Third parent, for a merge with at least three parents
HEAD~ or HEAD~1 One step along first parents
HEAD~2 or HEAD^^ Two steps along first parents
HEAD~5 Five first-parent steps

An ordinary non-merge commit has no second parent. A root commit has no parent at all. The requested ancestry must exist in the available history; shallow clones can limit how far Git can walk.

Follow a merge graph

A---B---C-------M  main (HEAD)
     \         /
      D-------E    feature

Here, assuming M was created by merging feature into main, M^1 is C, M^2 is E, and M~2 is B. The first parent records the branch tip on which that merge was made; it is not a permanent label for whichever branch is now called main.

Operators can be combined. HEAD^2~2 first selects the second parent, then follows its first-parent chain twice. HEAD~2^2 performs those operations in the opposite order and requires the selected ancestor to have a second parent.

Use the notation in commands

git show 'HEAD^'
git diff HEAD~3 HEAD
git log HEAD~10..HEAD --oneline
# Limit output to ten commits instead:
git log -10 --oneline

The range excludes commits reachable from HEAD~10 and includes those reachable from HEAD. In a merge history it can contain more than ten commits. A diff between two endpoints compares their trees, regardless of how many commits connect them.

git reset --soft HEAD~1 moves the branch to its first parent while retaining index and working-tree contents. git revert -m 1 MERGE instead reverses a merge's change relative to parent one by creating another commit.

Shell quoting

Windows Command Prompt uses ^ as an escape character. Quote the revision as "HEAD^", or use HEAD~1 when you mean the first parent. Quoting revision expressions is also a useful habit in other shells.

See Git revision syntax.

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting