0

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
  • 5,884
  • 11
  • 54
  • 82

1 Answers1

2

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
  • 17,132
  • 3
  • 30
  • 49
  • Ah, thanks, I thought that was what HEAD^ was for, now I know it's previous and commit parent. btw, you said 'git diff' but I thought that was, according to diagram 'git diff' is working and stage/index not last commit? – Neil Walker Sep 11 '19 at 12:43
  • @NeilWalker Haha, my turn to thank you ;-) I've been answering too hastily but you're right. Editing. I'll also add apart about `HEAD^` – Romain Valeri Sep 11 '19 at 12:44