Script to verify a signature with GPG

If you add --status-fd <fd>, gpg will output computer-readable status text to the given file descriptor (1 for stdout). For example:

$ gpg --status-fd 1 --verify authorized_keys.txt 
gpg: Signature made 2012-08-18T19:25:12 EEST
gpg:                using RSA key D24F6CB2C1B52632
[GNUPG:] SIG_ID BOn6PNVb1ya/KuUc2F9sfG9HeRE 2012-08-18 1345307112
[GNUPG:] GOODSIG D24F6CB2C1B52632 Mantas Mikulėnas <[email protected]>
gpg: Good signature from "Mantas Mikulėnas <[email protected]>"
gpg:                 aka "Mantas Mikulėnas <[email protected]>"
[GNUPG:] VALIDSIG 2357E10CEF4F7ED27E233AD5D24F6CB2C1B52632 2012-08-18 1345307112 0 4 0 1 2 00 2357E10CEF4F7ED27E233AD5D24F6CB2C1B52632
[GNUPG:] TRUST_ULTIMATE

Then just discard the default output (by redirecting 2> /dev/null) and check for VALIDSIG fingerprint.

I use the following:

fprint="2357E10CEF4F7ED27E233AD5D24F6CB2C1B52632"

verify_signature() {
    local file=$1 out=
    if out=$(gpg --status-fd 1 --verify "$file" 2>/dev/null) &&
       echo "$out" | grep -qs "^\[GNUPG:\] VALIDSIG $fprint " &&
       echo "$out" | grep -qs "^\[GNUPG:\] TRUST_ULTIMATE\$"; then
        return 0
    else
        echo "$out" >&2
        return 1
    fi
}

if verify_signature foo.txt; then
    ...
fi

You will probably need to remove the TRUST_ULTIMATE check, but keep VALIDSIG.