Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GPG key exists in the list?

Tags:

bash

shell

gnupg

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!

like image 409
LosYear Avatar asked May 01 '15 11:05

LosYear


2 Answers

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.
like image 84
Jens Erat Avatar answered Sep 19 '22 14:09

Jens Erat


You can do:

[[ $(gpg --list-keys | grep -w KEY) ]] && echo "Key exists" ||
gpg --keyserver SERVER --recv-keys  KEY

Additional (for apt keyring):

[[ $(apt-key list | grep -w KEY) ]] && echo "Key exists" ||
gpg --keyserver SERVER --recv-keys  KEY

If apt-key is available

like image 38
Jahid Avatar answered Sep 21 '22 14:09

Jahid