14

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!

LosYear
  • 423
  • 2
  • 6
  • 14

3 Answers3

14

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.
Community
  • 1
  • 1
Jens Erat
  • 37,523
  • 16
  • 80
  • 96
  • `gpg --list-keys` doesn't list all keys. – Jahid May 01 '15 at 12:37
  • 1
    `gpg --list-keys` lists all keys available in the _currently used keyring_. If the key is in whichever other keyring, this won't help you at using it. `apt-key list` will only list keys in the apt package manager's keyring -- this does not seem to be what the OP is trying to do. – Jens Erat May 01 '15 at 12:49
1

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

Jahid
  • 21,542
  • 10
  • 90
  • 108
  • 1
    Be aware that `apt-key` only works on the `apt` package manager's keyring, and not the user's one. This is very likely not what the OP intends to do. – Jens Erat May 01 '15 at 12:50
  • @JensErat, it seems I misinterpreted OP's intention. `gpg --list-keys` is the way to go – Jahid May 01 '15 at 13:24
  • Some years later, apt-key is deprecated https://manpages.ubuntu.com/manpages/impish/man8/apt-key.8.html – Ondřej Kolín Jun 28 '22 at 08:33
0

The correct way to do it is running the following command

gpg --keyserver hkp://keyserver.ubuntu.com -k [your-key-id]

Kyrol
  • 3,475
  • 7
  • 34
  • 46
kerner1000
  • 3,382
  • 1
  • 37
  • 57