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.
It is a wildcard for every part of the cron schedule expression. So * * * * * means every minute of every hour of every day of every month and every day of the week . 0 1 * * * - this means the cron will run always at 1 o'clock. * 1 * * * - this means the cron will run each minute when the hour is 1.
Crontab date/time fieldsRanges are two numbers separated with a hyphen. The specified range is inclusive. For example, 8-11 for an "hours" entry specifies execution at hours 8, 9, 10 and 11. Lists are allowed.
When cron executes a job, it doesn't load the environmental variables from files like ~/. bashrc, ~/. bash_profile, /etc/profile, and others. This is because cron runs jobs from a non-interactive, non-login shell.
One of the most frequent causes for the crontab job not being correctly executed is that a cronjob does not run under the user's shell environment. Another reason can be – not specifying the absolute path of the commands used in the script.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With