bash GPG 密钥存在于列表中吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29986413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 12:54:31  来源:igfitidea点击:

GPG key exists in the list?

bashshellgnupg

提问by LosYear

I want to create a shell script and I haven't worked with it before. There is a command for gpg:

我想创建一个 shell 脚本,但我以前没有使用过它。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!

问题是如果已经添加了密钥,我不想运行这个命令。有什么方法可以检查密钥列表中是否存在密钥?谢谢!

采纳答案by Jens Erat

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 grepafterwards as proposed by others in the comments, this will get horriblyslow for larger numbers of keys in the keyring. Run

运行gpg --list-keys [key-id](或缩写的 command -k),如果存在匹配的键,则返回码为 0(成功),否则返回码为 0(失败)。不要grep像其他人在评论中提出的那样列出所有密钥,然后再列出密钥,对于密钥环中的大量密钥,这将变得非常缓慢。跑

gpg --list-keys [key-id] || gpg --keyserver [server] --recv-keys [key-id]

to fetch missing keys, possibly discarding the first gpgcall's output (gpg --list-keys [key-id] >/dev/null 2>&1 || ...), as you're only interested in the return code.

获取丢失的键,可能会丢弃第一个gpg调用的输出 ( gpg --list-keys [key-id] >/dev/null 2>&1 || ...),因为您只对返回码感兴趣。

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.
  • 不时更新密钥可能是获取撤销的合理做法
  • 尤其是不应使用短密钥 ID,如果可能,请使用整个指纹。

回答by Jahid

You can do:

你可以做:

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

Additional (for apt keyring):

附加(对于 apt 钥匙圈):

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

If apt-keyis available

如果apt-key有空