Alex Rivera | Logout

Validate if commit exists

Asked 2010-11-08T20:54:01.467
22

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
Edit
Report

1 Answer

4

You can look at the output of

git rev-list HEAD..$sha

If this command fails because the sha1 does not exist at all in the repository, the exit code will be non-zero. If the output is empty, the commit is in the current branch, and if it is non-empty, it is not. So your script would look like

if revlist=`git rev-list HEAD..$sha 2>/dev/null` && [ -z "$revlist" ]; then
    :
fi

In case you already know that $sha really names a commit (as a SHA1 hash or in any other way), this simplifies to

if [ -z "`git rev-list HEAD..$sha`" ]; then
    :
fi
answered 2010-11-08T21:07:47.963

Your Answer