54

I've created a Cron task at my webhost to daily backup my database and I would like it to append the current date to the filename.

My Cron job looks like this

mysqldump -u username -pPassword db_name > www/db_backup/db_backup+date%d%m%y.sql

But the file I get is this: db_backup+date no file extension or date.

I've also tried this command

mysqldump -u username -pPassword db_name > www/db_backup/db_backup_'date +%d%m%y'.sql 

but that doesn't even give an file output.

What is the right syntax for getting the date appended to my file??

jww
  • 97,681
  • 90
  • 411
  • 885
Emil Devantie Brockdorff
  • 4,724
  • 12
  • 59
  • 76

4 Answers4

109
* * * * * echo "hello" > /tmp/helloFile_$(date +\%Y\%m\%d\%H\%M\%S).txt

You just need to escape the percent signs.

Other date formats: http://www.cyberciti.biz/faq/linux-unix-formatting-dates-for-display/

General Grievance
  • 4,555
  • 31
  • 31
  • 45
ethanneff
  • 3,083
  • 5
  • 23
  • 15
  • 4
    Working on CentOS 6.6. */10 * * * * /usr/bin/php -q /var/www/script.php > cron-job-log-$(date +\%Y\%m\%d\%H\%M\%S).txt – ursuleacv Apr 01 '15 at 16:47
  • 2
    The @ursuleacv answers works as expected. Here is my sample cron command: `08 10 * * * mysqldump -uYeBeSis_X2 -pPASWORDTHING dbName > /var/www/yebesis/mysqly/$(date +\%Y_\%m_\%d_\%I_\%M_\%p)_yebesis.sql` – caglaror Nov 21 '17 at 08:13
  • 2
    I guess he meant "escape percentages" because parentheses aren't escaped. After I escaped the percentage symbols it worked in my cron. – Miguel Ortiz Mar 04 '21 at 13:59
  • Note to self: BSD's `date` doesn't support the very convenient `-I` – Sridhar Sarnobat Jul 26 '21 at 06:58
  • Is it possible to set date to env variable to prevent writing it twice(for stdout and stderr)? both $() and backtikcs failed. – quant2016 Dec 15 '22 at 09:00
31

You should use `` instead of '' around the command you want to execute to generate the current date for your filename.

Zsolt Botykai
  • 50,406
  • 14
  • 85
  • 110
Fonzarely
  • 445
  • 4
  • 11
10

You must escape the format and use evaluation

mysqldump -u username -pPassword db_name > www/db_backup/db_backup_`date +\%d\%m\%y`.sql
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
RomAndNonES
  • 111
  • 1
  • 2
7

I need to create a new log file every time command is executed. So every day I should have a log like this /home/me/Logs/power_20151230.log The crontab line that I use is this:

00 8 * * * /home/me/power.py ON >> /home/me/Logs/power\_`date +20\%y\%m\%d`

Note the underscore character must be escaped too.

huzeyfe
  • 3,554
  • 6
  • 39
  • 49
edison
  • 121
  • 2
  • 6
  • 3
    It's not necessary to prepend `20` in front of `\%y`. It's better to use the upper-cased Y like this: `\%Y`. – thexpand Mar 22 '18 at 09:51