How to Get Only the Pub Part of GPG –list-public-keys

duplicityencryptiongpglinuxUbuntu

Okay, there is probably a better way to phrase this question. I am writing a script to configure my web servers on the first boot, but I hit a snag when generating the GPG key that will be used to encrypt backups with duplicity.

I am using this to generate the key without user interaction, but I need a way to get only the number under pub to throw on a file that will be used by duplicity later on the script.

I need this:

jamespond@penelope:~$ gpg --list-public-keys
/home/jamespond/.gnupg/pubring.kbx
----------------------------------
pub   rsa3072 2018-11-10 [SC] [expires: 2020-11-09]
      8304C92D7F77938BCE05A1619FC07FF505D443D3
uid           [ultimate] James Pond <root@madpony.co>
sub   rsa3072 2018-11-10 [E] [expires: 2020-11-09]

To become this:

jamespond@penelope:~$ gpg --list-public-keys | somecommand
8304C92D7F77938BCE05A1619FC07FF505D443D3

Is that possible? I looked at GPG's man page and it doesn't seem like there is a command for that, so I am guessing I would need to pipe –list-public-keys to sed? But I have no idea what regular expression I would need to use to get just that piece of the puzzle.

Thanks in advance!

Best Answer

First, you will want to use the --with-colons output mode for scripting. Then, to grab only the fingerprints of the public keys, I used sed to narrow down to only the pub part and cut to get to the 10th field of the fpr field:

gpg --list-public-keys --with-colons \
    | sed -ne '/^pub:/,/^fpr:/ { /^fpr:/ p }' \
    | cut -d: -f10

If you have multiple keys, it will print each of them on a line of its own.

Related Topic