I want to create a shell script and I haven't worked with it before. There is a command for gpg:
gpg --keyserver SERVER --recv-keys KEY
The problem is that I don't want to run this command if key has been already added. Is there any method to check that key exists in keys list? Thank you!
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