How to get the parent of a specific commit in Git
I have a commit number. I would like to get the previous commit number (parent). I need commits from the current branch.
git log --pretty=%P -n 1 "$commit_from"
To get Parent Commit
git cat-file -p commit_id
tree tree_id
parent parent_commit_id
[parent other_parent_commit_id] # present only in case of merge commits
author xxx <[email protected]> 1513768542 +0530
committer xxx <[email protected]> 1513768542 +0530
If ${SHA} is the commit you know and you want its parent (assuming it's not a merge commit and has only one parent):
git rev-parse ${SHA}^
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).