How to run gpg from a script run by cron? How to run gpg from a script run by cron? bash bash

How to run gpg from a script run by cron?


It turns out that the answer was easier than I expected. There is a --batch parameter missing, gpg tries to read from /dev/tty that doesn't exist for cron jobs. To debug that I have used --exit-on-status-write-error param. But to use that I was inspired by exit status 2, reported by echoing $? as Cd-Man suggested.


In my case gpg cant find home dir for using keys:

gpg: no default secret key: No secret key

gpg: 0003608.cmd: sign+encrypt failed: No secret key

So I added --homedir /root/.gnupg. The final command can looks like

echo 'password' | gpg -vvv --homedir /root/.gnupg --batch --passphrase-fd 0--output /usr/share/file.gpg --encrypt --sign /usr/share/file.tar.bz2


You should make sure that GPG is in your path when the cronjob is running. Your best guess would be do get the full path of GPG (by doing which gpg) and running it using the full path (for example /usr/bin/gpp...).

Some other debugging tips:

  • output the value of $? after running GPG (like this: echo "$?"). This gives you the exit code, which should be 0, if it succeded
  • redirect the STDERR to STDOUT for GPG and then redirect STDOUT to a file, to inspect any error messages which might get printed (you can do this a command line: /usr/bin/gpg ... 2>&1 >> gpg.log)