git,

Git: HEAD^ vs HEAD~

Sep 29, 2022 · 1 min read · Post a comment

Git HEAD is usually defined as the most recent commit on your current working branch. There are more than one “HEAD” variations which are going to be topic for this post.

Prerequisites

  • Git

Solution

Show the refs HEAD points at:

cat .git/HEAD

Output:

ref: refs/heads/main

Think of it as: HEAD -> refs/heads/main -> <commit-SHA1>.

Show the commit HEAD points at:

git show HEAD
git show @
git show

HEAD^ (HEAD^1)

HEAD^ points to the commit behind the latest one. The third one from the top could be pointed as HEAD^^ and so on. Keep in mind that HEAD^^ not equal to HEAD^2. That’s a different story in case you are dealing with merge commits when there are multiple parents involved.

If a commit has more than one parent: HEAD^2 points to the second parent hence use it on merge commits only.

HEAD~ (HEAD~1)

HEAD~ is basically the same as HEAD^. Therefore:
HEAD~1 = HEAD^1 (second one from the top or second last if you will),
HEAD~2 = HEAD^^ (third one from the top), etc.

Top commit = latest one = current one all refer to HEAD in this case. A detached HEAD is not part of this post though.

If a commit has more than one parent: HEAD~2 points up two levels in the Git commit tree via the first parent.

Use HEAD~ whenever possible.

The big picture

HEAD vs HEAD~ vs HEAD^

Conclusion

HEAD^^ = HEAD~2
HEAD^^HEAD^2

Related posts:

To find more neat Git commands and hacks, simply browse the Git category. Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.

git