3

I was searching on doing a diff between working tree and last commit and came across this accepted answer at Stackoverflow.

Can someone explain what HEAD and HEAD~ is actually referring to as it wasn't explained in the answer and I can't figure it out from google. :)

enter image description here

Thanks.

Neil Walker
  • 6,400
  • 14
  • 57
  • 86

1 Answers1

4

First, to factually answer the initial need : "I was searching on doing a diff between working tree and last commit"

You'd have to simply

git diff HEAD

(HEAD is implied for most commands but diff is a bit different here, and yes git diff is different from git diff HEAD)


Now, the difference between HEAD and HEAD~ is quite simple :

HEAD is the pointer git uses to represent the current state being worked on, often a branch. (see the glossary)

~ means the designated commit's parent. So HEAD~ means "not last commit but the one before that"

With such a tree :

---> time direction this way --->

A---B---C <<< master <<< HEAD

HEAD would resolve to commit C, while HEAD~ would resolve to B


Edit to clarify about HEAD^

HEAD^ and HEAD~ both point (if we stick to our example) to B, but it shouldn't mislead you into thinking they're the same.

<someCommit>^N (where N=1 if not explicitly given) means the designated commit's Nth parent when said commit has multiple parents. For a classic two parents merge, if HEAD points to the merge commit, parents can be found with HEAD^ and HEAD^2.

<someCommit>~N(again, N defaulting to 1) , in the other hand, means Nth ancestor of said commit, meaning you go back N commits in the past, following only one parent each time. For better clarity, in our example, HEAD~2 would designate A

Romain Valeri
  • 19,645
  • 3
  • 36
  • 61