What Does HEAD~N Refer to in Git?

In git, ~N suffix added to HEAD points to the "N"-th ancestor commit relative to HEAD (or more specifically, from the first parent of the commit object that HEAD points to) in the current branch:

HEAD # pointer to the commit object

HEAD~1 # refers to the first parent of the commit object
HEAD~ # same as HEAD~1

HEAD~2 # refers to first parent of the first parent (or the "grandparent")
HEAD~~ # same as HEAD~2

HEAD~3 # refers to first parent of the "grandparent"
HEAD~~~ # same as HEAD~3

# ...

To understand this better, consider for example, the following visualization:

--> latest commits this way -->
                     HEAD
                      |
... -> U -> V -> W -> X -> ...

In the example above, since HEAD is pointing to "X", the following would be true:

HEAD # points to "X"
HEAD~ # refers to "W" (i.e. 1 commit older than HEAD)
HEAD~2 # refers to "V" (i.e. 2 commits older than HEAD)
HEAD~3 # refers to "U" (i.e. 3 commits older than HEAD)
# ...

For a more practical example, let's consider the following git commit history:

commit 3ba53ff050ef253058088eff5
Author: Designcise
Date:   Thu Dec 9 17:39:20 2021 +0100

    Updated tests

commit 66db03591ccb5581edf0044dfe
Author: Designcise
Date:   Thu Dec 2 17:53:47 2021 +0100

    Refactoring & updated license

commit 34bc04751b3b5581ed7de32cdb
Author: Designcise
Date:   Mon Nov 15 03:00:30 2021 +0100

    Added coverage badges to readme

commit 76af06471c3a5281ff7fe38ce9
Author: Designcise
Date:   Sun Nov 14 12:34:42 2021 +0100

    Updated author list in readme

commit 45db03581b3b5581ed7cc44dbc
Author: Designcise
Date:   Fri Nov 5 22:06:47 2021 +0100

    Updated readme

...

If you were to, for example, run the git checkout HEAD~3 command, then the HEAD would move/point to the commit with the id "76af06471c3a5281ff7fe38ce9".


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.