Understanding the Caret (^) Operator in Git
In the last blog, we explored the tilde (~) operator for moving back along the commit chain:
HEAD~1= parentHEAD~2= grandparentHEAD~3= great-grandparent
But ~ only works in linear history. What happens in a merge commit, where there are multiple parents?
This is where the caret (^) operator comes in.
Example Setup
Let’s say we have a history like this:
Here:
-
Mis a merge commit. -
It has two parents:
- First parent =
C2(main branch) - Second parent =
F1(feature branch).
- First parent =
Using the Caret Operator
HEAD^orHEAD^1→ first parent (usually the branch you merged into).HEAD^2→ second parent (the branch that was merged).
git rev-parse HEAD^
# shows commit ID of first parent
git rev-parse HEAD^2
# shows commit ID of second parent
If you try HEAD^3 — it won’t work, because a merge commit only has two parents.
Difference Between ~ and ^
-
Tilde (
~) moves back along the first-parent chain only.HEAD~1→ parentHEAD~2→ grandparent
-
Caret (
^) lets you explicitly pick a parent in a merge commit.HEAD^1→ first parentHEAD^2→ second parent
They can also be combined:
git rev-parse HEAD^2~1
Meaning:
HEAD^2= second parent of HEAD~1= parent of that commit
Practical Use Case: Git Diff
Suppose you want to compare the merge commit’s second parent with your main branch:
git diff HEAD^2 HEAD
Or even:
git diff HEAD^2~1 HEAD^1
This is powerful for debugging merges, understanding what changed, or reviewing history.
Time Travel with Caret
Just like with ~, you can use caret with git switch:
git switch --detach HEAD^2
This moves HEAD to the second parent of the merge commit.
Summary
~operator → walks back the first-parent chain.^operator → selects a specific parent in a merge commit.HEAD^1= first parent (default).HEAD^2= second parent (the branch being merged).- You can combine them (
HEAD^2~1) for more complex navigation. - Works in
git diff,git log,git show, andgit switch.
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! 🎉