tags:

views:

2455

answers:

5

I have a script that has a part that looks like that:

for file in `ls *.tar.gz`; do
  echo encrypting $file
  gpg --passphrase-file /home/$USER/.gnupg/backup-passphrase \
    --simple-sk-checksum -c  $file
done

For some reason if I run this script manually, works perfectly fine and all files are encrypted. If I run this as cron job, echo $file works fine (I see "encrypting <file>" in the log), but the file doesn't get encrypted and gpg silent fails with no stdout/stderr output.

Any clues?

A: 

make sure the user that is running the cron job has the permissions needed to encrypt the file.

Nick Berardi
A: 

I've came across this problem once.

I can't really tell you why, but I dont think cron executes with the same environment variable as the user do.

I actually had to export the good path for my programs to execute well. Is gpg at least trying to execute?

Or are the files you are trying to encypt actually in the current directory when the cron executes?

Maybe try to execute a echo whereis gpg and echo $PATH in your script to see if it's included... Worked for me.

skinp
+1  A: 

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)
Cd-MaN
+3  A: 

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.

Marcin
Thank you for this, we were having the exact same issue!
latortuga
A: 

@skinp Cron jobs are executed by sh, whereas most modern Unixes use bash or ksh for interactive logins. The biggest problem (in my experience) is that sh doesn't understand things like:

export PS1='\u@\h:\w> '

which needs to be changed to:

PS1='\u@\h:\w> '
export PS1

So if cron runs a shell script which defines an environment variable using the first syntax, before running some other command, the other command will never be executed because sh bombs out trying to define the variable.

dr-jan