Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
3  
if you don't want $HOME/cron.log to be overwritten, use >> not > – Dave Cheney Feb 27 '10 at 8:01
up vote 16 down vote accepted

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.

share|improve this answer
    
This is how I've done it in the past, works great. – ongle Feb 27 '10 at 1:42
    
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

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).

share|improve this answer
1  
The link is dead mate. Change it to mpcabd.xyz/adding-a-timestamp-to-command-output-in-linux – Cleankod Nov 21 '15 at 12:11
    
tks 4 the headsup! – tony gil Nov 22 '15 at 1:23
    
@benjamin tks for the edit! :) – tony gil Nov 26 '15 at 12:29
1  
Very nice, thanks for this! – Danijel Jan 15 at 13:09

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
share|improve this answer

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

share|improve this answer
    
Please add more info and example. – Danijel Jan 15 at 13:10

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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