Using date command in cron job

Posted on

I had to set a cron job to back up mysql database and its format I wanted is like this

back_up_YYYY_MM_DD.sql

And here was my first initial configuration that I added to /etc/crontab

00 11   * * *   a_user   mysqldump -u root -pSomePass db > /home/a_user/www/sql_backup/back_up_`date +%Y_%d_%m`.sql

Actually, I noticed a strange syntax color at the end of the line in Vim. I thought it is just misparsing so that I ommited it.

And here was the output in /var/log/syslog

Jan  4 11:00:01 a_user CRON[3427]: (a_user) CMD (  mysqldump -u root -pSomePass db > /home/a_user/www/sql_backup/back_up_`date +)

Something was wrong as you can see; it was not complete.

In order to fix this, I had to escape the ‘%’ sign

00 11   * * *   a_user   mysqldump -u root -pSomePass db > /home/gizmo/www/sql_backup/back_up_`date +\%Y_\%d_\%m`.sql

Now, everything works fine :D