Understanding the Tilde (~) Operator in Git
In the last blog, we explored how to time travel in Git by switching to specific commits. In this one, let’s dive into a powerful operator that helps us move relative to HEAD without needing to copy-paste commit IDs: the tilde (~) operator.
Setup Example
Suppose we created a repository with three commits:
git init project9
cd project9
echo "first" > file.txt
git add .
git commit -m "First commit"
echo "second" >> file.txt
git commit -am "Second commit"
echo "third" >> file.txt
git commit -am "Third commit"
Check history:
git log --oneline
Output:
61f19cb Third commit
2699422 Second commit
a1b2c3d First commit
Using git rev-parse with HEAD
To print the commit ID of HEAD:
git rev-parse HEAD
Output:
61f19cb...
Moving Back with ~
The tilde operator lets you move up the ancestry chain:
git rev-parse HEAD~1
Output:
2699422...
This is the first parent (previous commit).
git rev-parse HEAD~2
Output:
a1b2c3d...
This is the grandparent (two commits behind HEAD).
And so on:
HEAD~0→ current commit (same asHEAD)HEAD~1→ parent commitHEAD~2→ grandparentHEAD~3→ great-grandparent
With Merges
In a linear history, HEAD~n is straightforward.
But what if there’s a merge commit?
Here:
HEAD~1= the first parent (usuallymain)HEAD~2= the parent of the first parent (grandparent)
⚡ But how do we access the other parent of a merge? That’s where the caret (
^) operator comes in — which we’ll cover in the next blog.
Summary
git rev-parseprints commit IDs for references.- The tilde (
~) operator moves back in the ancestry chain. HEAD~1= parent,HEAD~2= grandparent, etc.- Useful for
git diff,git log,git show, or any command that accepts commit IDs. - In merges,
~follows the first parent chain only.
Keep Learning 🚀
👉 Subscribe to Learning Ocean – Subscribers get coupon codes for my courses, early access to blogs and courses, and even exclusive YouTube videos.
👉 My YouTube Channel – More videos, more fun, and lots of learning!
👉 📺 Watch this topic in video form
Stay curious, keep coding, and let’s make learning fun together! 🎉