How to get the parent of a specific commit in Git

Viewed 47398

I have a commit number. I would like to get the previous commit number (parent). I need commits from the current branch.

12 Answers

You can use git rev-parse for this.

# Output hash of the first parent
git rev-parse $commit^

# Nth parent
git rev-parse $commit^N

# All parents
git rev-parse $commit^@

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.  ^<n> means the <n>th
     parent (i.e.  <rev>^ is equivalent to <rev>^1). As a
     special rule, <rev>^0 means the commit itself and is
     used when <rev> is the object name of a tag object that
     refers to a commit object.

 ...

 <rev>^@, e.g. HEAD^@
     A suffix ^ followed by an at sign is the same as listing
     all parents of <rev> (meaning, include anything
     reachable from its parents, but not the commit itself).

If you are looking for the parent of a merge commit

# Output sha of the first parent
git rev-parse $commit^1

# Output sha of the second parent
git rev-parse $commit^2

# All parents sha
git rev-parse $commit^@

For the full details: git log 4c7036e807fa18a3e21a5182983c7c0f05c5936e^ -1

For just the hash: git log 4c7036e807fa18a3e21a5182983c7c0f05c5936e^ -1 --pretty=%H

The most efficient way

With git rev-parse <commit-ish>^@, parents will be displayed on a different line, making it easy to both view and parse.

Be careful not to use <commit-ish>^, this will only show the first parent, not the parents.

Other ways to inventory

Replacing -pretty=%P below with -pretty=raw will also work, the latter will show more content.

  1. git cat-file -p <commit-ish>^{}.
  2. git show -p <commit-ish>^{} --pretty=%P --no-patch.
  3. git log --pretty=%P -n 1 <commit-ish>.
  4. git rev-list --parents -n 1 <commit-ish>.

The previous commit of a commit can be reached also using the ~ notation:

git log aabbccdd~1
 curl \
  -H "Accept: application/vnd.github.v3+json" \
  https://api.github.com/repos/vadz/libtiff/commits/1ad0b2b5d3f1bd8bfe34d81e7742966cffeab6eb
...
  "parents": [
    {
      "sha": "86a4d8ea94037f4b440caef8f5e4466adb99c536",
      "url": "https://api.github.com/repos/vadz/libtiff/commits/86a4d8ea94037f4b440caef8f5e4466adb99c536",
      "html_url": "https://github.com/vadz/libtiff/commit/86a4d8ea94037f4b440caef8f5e4466adb99c536"
    }
  ],
...
Related