38

I have a crontab like this on a LAMP setup:

0 0 * * * /some/path/to/a/file.php > $HOME/cron.log 2>&1

This writes the output of the file to cron.log. However, when it runs again, it overwrites whatever was previously in the file.

How can I get cron to output to a file with a timestamp in its filename?

An example filename would be something like this: 2010-02-26-000000-cron.log

I don't really care about the format, as long as it has a timestamp of some kind.

Thanks in advance.

  • 8
    if you don't want $HOME/cron.log to be overwritten, use >> not > – Dave Cheney Feb 27 '10 at 8:01
67

Try:

0 0 * * * /some/path/to/a/file.php > $HOME/`date +\%Y\%m\%d\%H\%M\%S`-cron.log 2>&1

Play around with the date format, if you like; just be sure to escape any % like \%, as above.

  • And let me generally suggest an approach to file names like 0 0 * * * /some/path/to/a/file.php > $HOME/scriptname-date +\%Y\%m\%d\%H\%M\%S.log – Kristian Oct 17 '15 at 11:14
  • If you need it a little more human readable try: date +\%Y\ \%m\ \%d\ \%H:\%M:\%S-cron.log – DevilCode Apr 4 '16 at 13:35
  • 4
    @DevilCode, yes, although spaces in filenames aren't very conventional in Unix. Hyphens or underscores might be a better option: date +\%Y-\%m-\%d_\%H:\%M:\%S-cron.log. – fission Apr 4 '16 at 23:47
  • 1
    Those freaking escape characters always get me. Thanks for the reminder! – Tony-Caffe Oct 8 at 0:21
14

i would highly recommend that you save everything into the same file, using timestamp, as explained here.

remove

2>&1

and run it thru the timestamping script before saving it to log file (as explained in above link).

6

You can also append your output to the log file by doing it like this:

0 0 * * * /some/path/to/a/file.php >> $HOME/cron.log 2>&1
0

I modified the script like this:

`/bin/date +\%Y\%m\%d`.log
-2

I solved this problem; just add the date path (/bin/date) before the date command.

  • 2
    Please add more info and example. – Danijel Jan 15 '16 at 13:10
-2
@daily /some/path/to/a/file.php 2>&1 > $HOME/$(date +\%Y\%m\%d\%H\%M\%S)-cron.log
  • 5
    This would need a lot of explanation. – Sven Feb 22 at 17:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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