Cron: variables based on command output

I had a problem with a cron job, a not-so-annoying but daily-repeating one. It's like a drill boring your mind slowly. Every time I got an email with the failing report the drill bit made more internal damage.

/bin/sh: -c: unexpected EOF while looking for matching `''
/bin/sh: -c: line 1 systax error: unexpected end of file

I was just trying to put a date into a file's name to backup a SpamAssassin bayes database, something like bayes-201508, but it seemed that it didn't like to cron. I've tried it many ways:

30 * * * * /usr/bin/sa-learn --backup > /data/bayes-$(date +%Y%m).back
30 * * * * /usr/bin/sa-learn --backup > /data/bayes-$(date '+%Y%m').back
30 * * * * /bin/bash -l -c '/usr/bin/sa-learn --backup > /data/bayes-$(date +%Y%m).back'

Thought it was caused to crontabs being running with sh instead of bash but at last nothing seemed to work in the proper way. I've experienced similar problems other times so I've decided to write the solution here: just escape the date call arguments:

30 * * * * /usr/bin/sa-learn --backup > /data/bayes-$(date +\%Y\%m).back

And it will work like a charm. Hope this helps in the future.

sysadmin

About the author

Óscar
has doubledaddy super powers, father of Hugo and Nico, husband of Marta, *nix user, Djangonaut and open source passionate.