Search code examples
shellgnupg

how to print only primary uid of a gpg key in bash?


I have a finger print. I know I can do gpg -k <finger print> to print out all pubkey info. But I only want to get the primary uid of a key which have multiple uids. What is the canonical way to do this? I knew I can try to grep the first uid occurrence. But I do not know how stable that thing is.


Solution

  • I believe you're looking for the --with-colons option, which provides stable output for parsing by scripts. Given a key like this:

    pub   rsa2048/0x362D63A80853D4CF 2013-06-21 [SC]
          3E70A502BB5255B6BB8E86BE362D63A80853D4CF
    uid                   [ultimate] Lars LastName <lars@...>
    uid                   [ultimate] keybase.io/larsks <larsks@...>
    sub   rsa2048/0x042DF6CF74E4B84C 2013-06-21 [S] [expires: 2023-07-01]
    sub   rsa2048/0x426D9382DFD6A7A9 2013-06-21 [E]
    sub   rsa2048/0xEE1A8B9F9369CC85 2013-06-21 [A]
    

    The --with-colons output looks like this:

    tru::1:1615472480:1656257313:3:1:5
    pub:u:2048:1:362D63A80853D4CF:1371778249:::u:::scESCA::::::23::0:
    fpr:::::::::3E70A502BB5255B6BB8E86BE362D63A80853D4CF:
    uid:u::::1416450403::C2B1F8BE099BCF889677DBC639C4427C04BC230A::Lars LastName <lars@...>::::::::::0:
    uid:u::::1407979245::E8B853E07D5D3F9BAD96435FA508017A644467AE::keybase.io/larsks <larsks@...>::::::::::0:
    sub:u:2048:1:042DF6CF74E4B84C:1371778249:1688234376:::::s::::::23:
    fpr:::::::::FDE8364F7FEA3848EF7AD3A6042DF6CF74E4B84C:
    sub:u:2048:1:426D9382DFD6A7A9:1371778250::::::e::::::23:
    fpr:::::::::01A14A356BFE207E7CF6EAFE426D9382DFD6A7A9:
    sub:u:2048:1:EE1A8B9F9369CC85:1371778250::::::a::::::23:
    fpr:::::::::D73B9191F0AF110B229FF242EE1A8B9F9369CC85:
    

    This output is stable, so you can just look for the first uid element:

    gpg --with-colons -k <fingerprint> |
      awk -F: '$1=="uid" {print $10; exit}'
    

    Which given the above data would produce:

    Lars LastName <lars@...>
    

    The --with-colons output format is documented here.