I am having an issue that I can not find any information for while doing an extensive google search.

I have a linux cron, running via crontab, that works great until I try to add a variable date to the title of the file. BUT.. When I run the same command outside the cron, just from the command line, it works fine.. Also, the cron does work if I take out the date part.

Command line code that works:

sudo mysqldump -h mysql.url.com  -u user -pPassword intravet sites | gzip > /mnt/disk2/database_`date '+%m-%d-%Y'`.sql.gz

Cron that works:

15 2 * * * root mysqldump -h mysql.url.com -u user -pPassword intravet sites | gzip > /mnt/disk2/database.sql.gz

Cron that DOESN'T work:

15 2 * * * root mysqldump -h mysql.url.com -u user -pPassword intravet sites | gzip > /mnt/disk2/database_`date '+%m-%d-%Y'`.sql.gz

I am not understanding why I can not use the date function while inside a cron? Everything I find says I can, but in practice, I can not.

Server details: Ubuntu 12.04.5

Thank you for any insight.

share|improve this question
    
From the man page: A "%" character in the command, unless escaped with a backslash (\), will be changed into newline characters, and all data after the first % will be sent to the command as standard input. – dg99 Apr 17 '15 at 20:39
up vote 2 down vote accepted

You just need to use escaping % sign

* * * * * touch /tmp/foo_`date '+\%m-\%d-\%Y'`.txt

Result:

[root@linux tmp]# ls -l /tmp/foo_*
-rw-r--r-- 1 root root 0 Apr 18 02:17 /tmp/foo_04-18-2015.txt
share|improve this answer
    
Neither of these work, I did some research and found out that shell is not, by default, accessible from the cron tab. I still have not solved the issue, but I believe this to be the cause. – Jason Apr 20 '15 at 15:54
    
what do you mean shell isn't accessible from crontab? cron use default SHELL=/bin/bash variable – Satish Apr 20 '15 at 16:35
    
Ok.. So my shell path was incorrect, THEN adding backslash to escape fixed my issue! Thank you guys so much.. – Jason Apr 20 '15 at 19:02
    
if you find answer is help full then please click on Answer to get point – Satish Apr 20 '15 at 19:24

Try replacing the backticks with $() and escaping your %s, such as:

15 2 * * * root mysqldump -h mysql.url.com -u user -pPassword intravet sites | gzip > /mnt/disk2/database_$(date '+\%m-\%d-\%Y').sql.gz

I only mention removing the backticks because you will end up having all kinds of escaping problems later in your coding endeavours. Stick with using $() for command substitution.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.