Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the parents of a merge commit in Git?

Tags:

git

merge

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.

like image 583
Casebash Avatar asked Jan 30 '12 04:01

Casebash


People also ask

How do I find a committed parent?

You can use git rev-parse for this. These constructs are explained in git help rev-parse : <rev>^, e.g. HEAD^, v1. 5.1^0 A suffix ^ to a revision parameter means the first parent of that commit object.

How many parents does merge commits have?

Unlike other commits, the merge commit is a commit which has multiple (generally two) parents. For instance, when a branch named feature is merged with master, a new commit is created on the branch master which has two parents, the previous head of master and the head of feature.

What is the parent of a commit?

The parent commit is the commit this current commit is based on. Usually: When you git commit normally, the current commit becomes the parent commit of the new commit that's introduced by the command.

How many parents can a commit have?

A commit object may have any number of parents. With exactly one parent, it is an ordinary commit. Having more than one parent makes the commit a merge between several lines of history. Initial (root) commits have no parents.


2 Answers

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.

like image 168
Cascabel Avatar answered Oct 08 '22 02:10

Cascabel


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

git show --pretty=raw 3706454
like image 25
user1483344 Avatar answered Oct 08 '22 04:10

user1483344