Git
HEAD reference
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..HEAD
This 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~3
Tilde numbering is the most practical way to roll back multiple commits in one command.
Exercise 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".
Show example 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"
Test yourself
-
What does the expression HEAD~2 represent in Git?
- The ancestor commit 2 steps before the current HEAD commit
- 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
Show answer
The ancestor commit 2 steps before the current HEAD commit — In tilde syntax, HEAD~n points to the ancestor commit n steps back along the first-parent lineage.
-
Move two commits back
git reset --soft ____
Show answer
git reset --soft HEAD~2
-
Ancestor references
- 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
Next lesson: Summary - Reset