0%

Fix GPG Encryption Failures in Crontab

I ran into this while writing a shell script that encrypts files automatically every day. A gpg command that worked perfectly in an interactive shell failed once I put it into a script and scheduled it with crontab.

After digging into it a bit, I found that running GPG from cron usually requires two extra arguments.

For example, if I want to encrypt testfile.txt for the public key belonging to test@knktc.com, I would normally use a command like this from the shell:

1
gpg -ear test@knktc.com --trust-model always --yes ./testfile.txt

At first I assumed that dropping the same command into a cron-triggered script would work the same way. A few minutes later it was clear that it did not.

Looking around, I found that if you want cron to execute GPG encryption correctly, you should also provide --no-tty and --homedir. The fixed command looks like this:

1
gpg --homedir=/root/.gnupg --no-tty -ear test@knktc.com --trust-model always --yes ./testfile.txt

With these two arguments:

  • Cron can find the correct GPG home directory where the keys are stored.
  • GPG can run non-interactively in cron’s execution environment.

After that, the scheduled encryption task works as expected.

如果我的文字帮到了您,那么可不可以请我喝罐可乐?