Today, I was trying to add a cron job for mysql database backup using crontab -e, everything went well when I tried the command at console, (backup local MySQL database into a folder and removes older then 5 days backups, I got it from
mysqldump -uroot -ppassword  --all-databases | gzip > /var/www/nginx-default/mysql-backup/mysql-backup-`date +%Y-%m-%d`.sql.gz ;find /var/www/nginx-default/mysql-backup/* -mtime +5 -exec rm {} \; 

but when I did: 
# export EDITOR=vi  
# crontab -e
# m h  dom mon dow   command
 48 3  *   *   * mysqldump -uroot -ppassword  --all-databases | gzip > /var/www/nginx-default/mysql-backup/mysql-backup-`date +%Y-%m-%d`.sql.gz ;find /var/www/nginx-default/mysql-backup/* -mtime +5 -exec rm {} \;

It failed, then I tried replace the backticks with $( )
mysqldump -uroot -ppassword  --all-databases | gzip > /var/www/nginx-default/mysql-backup/mysql-backup-$(date +%Y-%m-%d).sql.gz ;find /var/www/nginx-default/mysql-backup/* -mtime +5 -exec rm {} \; 

failed still, after a few googling I find out in a blog post comment of Anonymous:
You CAN use a backtick operator in the command argument place in a crontab.

However, percent signs (%) in the command must be escaped with a backslash or else they will be interpreted as a newline.

From 'man crontab':
The ??sixth?? field (the rest of the line) specifies the command to be run. The entire command portion of the line, up to a newline or % character, will be executed by /bin/sh or by the shell specified in the SHELL variable of the crontab file.
Percent-signs (%) in the command, unless escaped with backslash (\), will be changed into newline characters, and all data after the first % will be sent to the command as standard input. There is no way to split a single command line onto multiple lines, like the shell?s trailing "\".

so the following is valid:

15 3 * * 0,2-6 echo ´date +\%a´


15 3 * * 0,2-6 echo $(date +\%a)

Failure to escape the backslash will result in a cron error:

/bin/sh: -c: line 1: unexpected EOF while looking for matching ´´'
/bin/sh: -c: line 2: syntax error: unexpected end of file

so, the correct command to use in crontab -e is:

 48 3  *   *   * mysqldump -uroot -ppassword  --all-databases | gzip > /var/www/nginx-default/mysql-backup/mysql-backup-$(date +\%Y-\%m-\%d).sql.gz ;find /var/www/nginx-default/mysql-backup/* -mtime +5 -exec rm {} \;

Leave a Reply.