165

Some Git commands take the parent as a revision; others (such as git revert), as a parent number. How can I get the parents for both cases?

I don’t want to use the graphical log command as that often requires scrolling down a long tree to find the second parent.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Casebash
  • 114,675
  • 90
  • 247
  • 350

2 Answers2

211

Simple git log <hash> called for a merge commit shows abbreviated hashes of its parents:

 $ git log -1 395f65d
 commit 395f65d438b13fb1fded88a330dc06c3b0951046
 Merge: 9901923 d28790d
 ...

git outputs parents according to their number: the first (leftmost) hash is for the first parent, and so on.

If all you want is just the hashes, the two equivalent choices are:

$ git log --pretty=%P -n 1 <commit>
$ git show -s --pretty=%P <commit>

git rev-list can also show the parents' hashes, though it will first list the hash for a commit:

$ git rev-list --parents -n 1 <commit>

If you want to examine the parents, you can refer to them directly with carats as <commit>^1 and <commit>^2, e.g.:

git show <commit>^1

This does generalize; for an octopus merge you can refer to the nth parent as <commit>^n. You can refer to all parents with <commit>^@, though this doesn't work when a single commit is required. Additional suffixes can appear after the nth parent syntax (e.g. <commit>^2^, <commit>^2^@), whereas they cannot after ^@ (<commit>^@^ isn't valid). For more on this syntax, read the rev-parse man page.

Maxim Belkin
  • 138
  • 1
  • 6
Cascabel
  • 479,068
  • 72
  • 370
  • 318
  • 3
    Answering my own question: the results of 'git rev-list --parents -n 1 ' are: . Ie, the parents are one numbered. – mikemaccana Jul 15 '13 at 13:35
  • You can also use git-parents https://github.com/danielribeiro/dotfiles/blob/master/bin/git-parents. Just put it in your PATH and call $ git parents ( defaults to HEAD) – Daniel Ribeiro Oct 08 '13 at 23:40
  • @jefromi, I really want that "Also note that the normal log output does show..." part to be on the top of your answer. :) – Adam Monsen May 09 '14 at 18:29
  • 3
    `git log` and `git show` output very different things when there's only one parent. Prefer `git log` if you want consistency. – Noel Yap Sep 29 '14 at 21:44
  • This answer doesn't work on my Ubuntu machine with `git (v2.17.1)`. I do not see `Merge` file in `git log -1` output. – mja Dec 22 '18 at 12:11
39

The following is the simplest way I've found to view the parents of a merge

git show --pretty=raw 3706454
user1483344
  • 391
  • 3
  • 3