How can I easily get a list of secret key IDs available to the current GnuPG user?

I want a hypothetical command gpg --foo which I can use for:

keyids=$( ( gpg --foo ) )
for keyid in "${keyids[@]}" ; do …

What is the gpg --foo command that will just get me the key IDs for my secret keys?


It takes several seconds to complete, but this works:

gpg --list-secret-keys --with-colons \
    2> /dev/null \
    | grep '^sec:' | cut --delimiter ':' --fields 5

Thanks to @dirkt and @grawity for pieces of this answer.


For version 2.1.15, the following works for me:

gpg --list-secret-keys --keyid-format short | grep sec | cut -d' ' -f 4

I'm not sure if the output format stayed identical among versions, so you may have to adapt the following commands if your version uses a differently formatted output.

  • 2
    If you want a format that stays identical, use --with-colons.
    – user1686
    Nov 27 '16 at 9:53
  • @grawity: I got curious and tried --with-colons, but it looks like you need to do extra mangling for the short form, and I don't know enough to do this reliably - always pick the last 8 chars?
    – dirkt
    Nov 27 '16 at 11:11

My option is using awk:

gpg --list-secret-keys --with-colons | awk -F: '$1 == "sec" {print $5}' 

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.