Date time format in UNIX crontab

12,068

Solution 1

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.

Solution 2

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.

Share:
12,068
bikey77
Author by

bikey77

Updated on June 05, 2022

Comments

  • bikey77
    bikey77 almost 2 years

    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?