Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date time format in UNIX crontab

I'm running a cron every 6 hours to backup my database. I want the filename to contain the date & time it was created in the following format:

mysqlbackup_22/5/2013_15:45.sql.gz

This is the command I run:

date=`date -d`; mysqldump -uusername -ppassword dbname | gzip > /path/to/dir/mysqlbackup_$date.sql.gz

What do I need to change date -d to?

like image 266
bikey77 Avatar asked Feb 14 '26 08:02

bikey77


2 Answers

If you use a date format like date +"%d-%m-%Y_%H:%M" in your crontab you may need to escape the % characters with a backslash, like this: date +"\%d-\%m-\%Y_\%H:\%M".

Many crons handle % specially by replacing them with newline and sending the following text as stdin to the command before it. See man 5 crontab for details.

like image 154
Jürgen Strobel Avatar answered Feb 17 '26 18:02

Jürgen Strobel


The + operator on date gives you the flexibility to specify the date in whatever way/format you want, as long as there's a variable for what you want. In this case, from man date:

   %d     day of month (e.g, 01)
   ...
   %H     hour (00..23)
   ...
   %m     month (01..12)
   %M     minute (00..59)
   ...
   %Y     year

So, you'd have:

date +"%d/%m/%Y_%H:%M"

Or, applying to your command:

date=`date +"%d-%m-%Y_%H:%M"`; mysqldump -uusername -ppassword dbname | gzip > /path/to/dir/mysqlbackup_$date.sql.gz

Note that I changed the forward slashes (/) in filenames to dashes (-) as you can't have forward slashes in unix/linux filenames.

like image 25
msb Avatar answered Feb 17 '26 19:02

msb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!