The error code of this command will be 0 if the commit exists, or 1 if not:
git rev-parse -q --verify "$sha^{commit}" > /dev/null
If you want an easier read, append && echo "exists" || echo "doesn't exist"
.
From the git rev-parse
docs:
--verify
Verify that exactly one parameter is provided, and that it can be turned into a raw 20-byte SHA-1 that can be used to access the object database. If so, emit it to the standard output; otherwise, error out.
If you want to make sure that the output actually names an object in your object database and/or can be used as a specific type of object you require, you can add the ^{type} peeling operator to the parameter. For
example, git rev-parse "$VAR^{commit}" will make sure $VAR names an existing object that is a commit-ish (i.e. a commit, or an annotated tag that points at a commit). To make sure that $VAR names an existing object of
any type, git rev-parse "$VAR^{object}" can be used.
-q, --quiet
Only meaningful in --verify mode. Do not output an error message if the first argument is not a valid object name; instead exit with non-zero status silently. SHA-1s for valid object names are printed to stdout on
success.
As a bonus, if you don't suppress the output, you can get the full sha.