Validate if commit exists

takeshin picture takeshin · Nov 8, 2010 · Viewed 9.7k times · Source

How to validate whether the commit with given sha exists in current branch?

There are many ways to parse outputs, but I need optimal way which returns boolean (for usage in bash script).

e.g.

sha=$1
if [ -z `git magic --validate $sha` ]; then
  echo "Invalid commit sha: $sha"
  exit 1
fi

Answer

Janne picture Janne · Feb 19, 2014
git rev-parse --quiet --verify <commit>

Does not actually verify that commit (I guess SHA1 is what is meant) exists. It verifies that there is an object in the database corresponding to the SHA1 provided. That is, if there is a blob or tree object that matches the SHA1, it will report that it exists, even if it is not a commit.

git rev-parse --quiet --verify <sha1>^{commit}

This will verify that the object exists and that it is an object that can be used as a commit (commit or annotated tag).