Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HEAD~ for a merge commit

Tags:

git

In Git, you can refer to the commit before HEAD using the shorthand HEAD~, and two before using HEAD~2, etc.

I have a repository that has a merge commit like the following:

A----B-------------F
      \           /
       C----D----E

HEAD = F, HEAD~ points to B, and HEAD~2 points to A. With a merge commit like this, is there a shorthand that would point to E?

like image 282
Dismissile Avatar asked Jul 28 '26 12:07

Dismissile


2 Answers

Yes; the ~ specifies the generation, but you can use ^ to specify the parent number, in the case of a merge.

git show HEAD^2

Will show the 2nd parent.

(The distinction is especially subtle since without a numeric argument both ~ and ^ show the same thing, the first parent of HEAD. This is because both ~ and ^ default to 1 without a numeric parameter. So they show the first parent (by depth) and the first parent (by breadth) which are of course the same.)

like image 134
Edward Thomson Avatar answered Jul 30 '26 02:07

Edward Thomson


I know you asked for commit E, but the shorthand for commit C is an even better example for understanding the difference between ^ and ~.

Here is the shorthand for C:

HEAD^2~2

e.g. 2nd parent of HEAD and then 2 jumps down the first-parent chain from there.

Try cloning this repo to see for yourself (look for the "clone" link):

http://vm.bit-booster.com/bitbucket/plugins/servlet/bb_net/projects/BB/repos/a/commits

enter image description here

And here's how the various shorthands covered in this answer resolve:

git show --no-patch --oneline HEAD
1286a9a F

git show --no-patch --oneline HEAD^2
9640db6 E

git show --no-patch --oneline HEAD^2~2
506916b C

Exercise for the reader: what's another way (using this repo) to write HEAD^2~3?

like image 28
G. Sylvie Davies Avatar answered Jul 30 '26 03:07

G. Sylvie Davies