Run gpg --list-keys [key-id]
(or the abbreviated command -k
), which will have a return code of 0 (success) if a matching key exists, or something else (failure) otherwise. Don't list all keys and grep
afterwards as proposed by others in the comments, this will get horribly slow for larger numbers of keys in the keyring. Run
gpg --list-keys [key-id] || gpg --keyserver [server] --recv-keys [key-id]
to fetch missing keys, possibly discarding the first gpg
call's output (gpg --list-keys [key-id] >/dev/null 2>&1 || ...
), as you're only interested in the return code.
Be aware that
- updating keys from time to time might be a reasonable thing to do to fetch revocations
- especially short key IDs should never be used, use the whole fingerprint if possible.