Trigger Your GPG Passphrase and Clear Your Agent's Cache

You may want to do this if you're using gpg or signing git commits in a script and don't want it to hang.
Under normal circumstances if you perform an action that requires your GPG
key you’ll
get interactively prompted for your passphrase. For example maybe you’re
signing a git commit. As soon as you run git commit it will prompt you.
Then, depending on your preference you may optionally cache your passphrase to avoid typing it every time. I have mine cached for 1 week (in seconds) with these settings:
$ cat ~/.config/gnupg/gpg-agent.conf
default-cache-ttl 604800
max-cache-ttl 604800
If you have a script where you’re programmatically creating signed git commits
or using GPG in general and your passphrase isn’t already cached this could
cause your script to not work since you may not get prompted for your
passphrase. For example maybe you’re doing a lot of things in parallel and in
background processes with &.
# Trigger a Prompt
You can run echo | gpg --clearsign to sign an empty string. It produces this
to stdout:
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA512
-----BEGIN PGP SIGNATURE-----
iQGzBAEBCgAdFiEEy+y1bxYCJ3b9uuO4klhWD+S1XkgFAml02icACgkQklhWD+S1
XkiQygv8D3T69f+4LB1rphkBGFMt3cEwQiBkBzTwvbOQ3qZdXMZRC0syNwxCwZSm
69VCYURIGumaT0JQmokpDdWMdQBc5RC/u4R/v05G0CcSbVO4/lYR6ayJ+cZhgNKW
nfiFynv2B+ezxA1F1cNMUnMZoF6Cz0WD3K2RvgV9wnnmXElHoFTykgz3hirM1l57
d40KqP1XwcDHxG0HrGkqdVxzsnMZRuZ/G+ZivCo6/PiJQPNYpveOx78pk/sQr8dt
yCR6cHVUO8OfBSUNF4nMvfL3ie4dPaMReQO23VbtcqaA3lc9opL+X4ypooTWm5r3
s4ojzmapYliS4wFGIBZ31tIdWCKjXed3Jidj/GmhpfgJ1anuRujPGEMTovRgTY1L
KOd0VSfuLpJrlZxQ/2RbHCQZKYrQ9dIMDrDoYJ4U3NCpzO991lRzsmaqWhr1S/7Z
BNwwJsR2LDqG0H3alQChqZu2ohQ8QUxEwQJX9U4l6mAMKLcm2K+jWRrj4Tllu0GG
/0SjCT+l
=nKzI
-----END PGP SIGNATURE-----
If your passphrase isn’t cached, you’ll get prompted, else it’ll just work.
You can run echo | gpg --clearsign > /dev/null to avoid printing to stdout
which produces no output unless there’s an error. This could be handy to do in
a script where you’re priming or triggering your GPG passphrase so you can do
something with GPG later on.
I have a little script to help update my Docker starter apps and I run the above in the script because my script does a lot of things in the background and creates signed git commits. I got tired of the script not running all the way through because my GPG passphrase happened to have expired.
# Clear Your Passphrase’s Cache
For testing purposes, or maybe you want to clear your agent’s cache you can run:
$ gpg-connect-agent reloadagent /bye
OK
I pretty much never run this command but when testing the above in the script I wanted a way to quickly clear the agent’s cache and that does the trick.
The video below covers both commands.
# Demo Video
Timestamps
- 0:24 – Use case
- 0:52 – Trigger your gpg passphrase
- 1:28 – Clear your cached passphrase
Have you done this before? Let me know below.