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
pub   rsa3072 2018-11-10 [SC] [expires: 2020-11-09]
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

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!

  • 1
    What version of gpg do you have? When I looked at the man page, under --list-public-keys, it said exactly what to do. Nov 22, 2018 at 15:56
  • @MichaelHampton Using GPG 2.2.8. Problem with --with-colons is that it also does not give me a readable format. My understanding is that duplicity only accept "8304C92D7F77938BCE05A1619FC07FF505D443D3" as input for --encryption-key (but I could be wrong).
    – user497477
    Nov 22, 2018 at 16:00
  • That's the wrong field. The field is listed on the pub line, not the uid line. Nov 22, 2018 at 16:01
  • @MichaelHampton Ah, I was looking at this the wrong way. Using the name on the uid line is accepted by duplicity (so --encryption-key="James Pond"). Thank you! :)
    – user497477
    Nov 22, 2018 at 16:06

1 Answer 1


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.

  • This is exactly what I was looking for, thank you! :)
    – user497477
    Dec 31, 2018 at 18:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy