Telling if a Git commit is a Merge/Revert commit

Viewed 21333

I am writing a script that requires checking whether a particular commit is a Merge/Revert commit or not, and I am wondering if there is a git trick for that.

What I came up with so far (and I definitely don't want to depend on the commit message here) is to check HASH^2 and see if I don't get an error, is there a better way?

9 Answers

I'm finding all answer over complicated and some even not reliable.
Especially if you want to do different actions for merge and regular commit.

IMO best solutions is to call git rev-parse using second parent expression ^2 and then check for an errors:

git rev-parse HEAD^2 >/dev/null 2>/dev/null && echo "is merge" || echo "regular commit" 

This works perfectly for me. Most of example above is just a decoration which just discards unwanted output.

And for windows cmd this works nicely too:

git rev-parse "HEAD^2" >nul 2>nul && echo is merge || echo regular commit

note quote characters

Yet another way to find a commit's parents:

git show -s --pretty=%p <commit>

Use %P for full hash. This prints how many parents HEAD has:

git show -s --pretty=%p HEAD | wc -w

If the output of the following command is 1, that will indicate it is an individual commit. If not, it is a merge commit

git cat-file -p $commitID | grep -o -i parent | wc -l

To check whether it's a merge commit,

# Use the FULL commit hash because -q checks if the entire line is matched.
git rev-list --merges --all | grep -qx <FULL_commit_hash>
echo $?    # 0 if it's a merge commit and non-zero otherwise

To check whether it's a revert commit, you'll have to go through the other answers.

Related