takeshin takeshin -4 years ago 177
Git Question

Validate if commit exists

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).


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

Answer Source

The rev-list | grep method works fine; there's the tiniest bit of overhead because git has to print out all the SHA1s for grep to see, but it's not really a big deal.

You can also do it with git merge-base if you like - if the merge base of the target commit and the branch is the target commit, the branch contains the target commit:

if [ "$(git merge-base $commit $branch)" = "$commit" ]; then

Either way you do it, note that rev-list and merge-base are going to be printing out SHA1s, so if the commit you're testing for inclusion is named by a branch or tag, you'll want to use git rev-parse to turn it into an SHA1 first.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download