HEAD reference
- Git course
- Intermediate
- Lesson 43/82
- 4 min
Learn to reference previous commits with HEAD~.
Tilde (~) syntax and ancestor commits
Instead of manually typing a commit hash in Git, you can append a tilde (~) to HEAD to reference ancestor commits directly. HEAD~1 (or simply HEAD~) specifies the parent commit right before the current one. HEAD~2 refers to two commits back, and HEAD~3 means three commits back.
# Go back 2 commits:
git reset --mixed HEAD~2
# Go back 3 commits:
git log --oneline HEAD~3..HEADThis notation allows you to count steps backward through history effortlessly.
Caret (^) vs Tilde (~) distinction
HEAD~ climbs straight up the ancestral lineage step by step. The caret (^) symbol, on the other hand, is primarily used to pick different parents on merge commits. On a linear branch, HEAD~1 and HEAD^ point to the exact same commit.
# Undo last 3 commits keeping them staged:
git reset --soft HEAD~3Tilde numbering is the most practical way to roll back multiple commits in one command.
Practice Hard reset two commits back
Reset two commits back with git reset --hard -q HEAD~2 and print the latest commit subject with git log -1 --format="%s".
Starter code
git init -q -b main
git config user.name "Eren"
git config user.email "eren@example.com"
echo "1" > veri.txt
git add veri.txt
git commit -qm "temel"
echo "2" > veri.txt
git commit -am -q "ikinci"
echo "3" > veri.txt
git commit -am -q "ucuncu"
# HEAD~2'ye hard reset at ve son commit basligini basSample solution
git init -q -b main
git config user.name "Eren"
git config user.email "eren@example.com"
echo "1" > veri.txt
git add veri.txt
git commit -qm "temel"
echo "2" > veri.txt
git commit -am -q "ikinci"
echo "3" > veri.txt
git commit -am -q "ucuncu"
git reset --hard -q HEAD~2
git log -1 --format="%s"Expected output
temel
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the expression HEAD~2 represent in Git?
- The ancestor commit 2 steps before the current HEAD commit Correct answer
- The diff of the last 2 files added to the staging area
- Only commits created within the last 2 hours
- The latest commit on branch number 2 in the repository
Explanation: In tilde syntax, HEAD~n points to the ancestor commit n steps back along the first-parent lineage.
2 Move two commits back
git reset --soft ____
git reset --soft HEAD~2
Explanation: HEAD~2 represents the ancestor commit 2 steps prior to the current commit.
3 Ancestor references
| Term | Meaning |
|---|---|
HEAD~1 |
Points to one ancestor commit back |
HEAD~3 |
Points to ancestor 3 commits back |
Tilde (~) |
Counts backwards along lineage |
Commit hash alternatifi |
Accesses ancestor without typing hash |