Before we look at the difference between HEAD~
and HEAD^
, let’s look at HEAD
without any modifier.
HEAD
The most recent commit on the current branch is the HEAD
of the branch. Commands that take a commit as a parameter will use HEAD
by default.
git show
is the same as
git show HEAD
You can also use the at sign (@
) as a shortcut for HEAD
git show @
HEAD^
The caret (^
) represents the commit’s parent.
We can display our log in a readable way with git log --oneline --graph
(see How to Improve Git Log).
* d780351 Add LICENSE.txt (HEAD)
* 25b2f97 Add plugin code
* 300d2a9 Add .gitignore
* 20dab1f Initial commit with README.md
Our most recent commit, at the top of the list (HEAD
), is Add LICENSE.txt.
To get our second to last commit, the parent of HEAD
(second from the top) which has the message Add plugin code, we can use
git HEAD^
The third commit from the top (the parent of the parent of HEAD
) can be targeted with
git HEAD^^
Warning: When numbers are used with ^
, they do not represent the number of ^
s.
HEAD^2
is NOT equivalent to HEAD^^
Using a number with ^
(e.g. HEAD^2
) comes into play when you have a git history that includes merge commits and is a topic for another blog post.
HEAD~
The tilde (~
) is a shortcut character for when you have multiple carets (^
) in a row.
HEAD~3
is equivalent to HEAD^^^
HEAD~5
is equivalent to HEAD^^^^^
If no number is specified, the default used is 1
, so
HEAD~
is equivalent to HEAD^
Recommendation
When working with git I often use ~
and almost never use ^
. Typically, I use HEAD
, HEAD~1
, and HEAD~2
and when things get more complicated than that, I target the commit by the unique SHA (e.g. git show 300d2a9
).
I tried to understand ^ vs ~ from this SO post: https://stackoverflow.com/questions/2221658/whats-the-difference-between-head-and-head-in-git
But this article is much easier to understand. Thanks Sal!
Linked to your article from the top answer in the SO comments btw.
Read about this topic from another source and found it difficult to understand. You have explained it very nice and are easy to understand.
Thanks Sal!