Ubuntu: How to add the logs to a crontab with time stamp



Question:

In crontab, I scheduled a daily backup script. Now when the cron executes the script the status are logged to a log file as shown below.

0 0 * * * /home/backup.sh > /home/groupz/db-backup/fbackup.log 2>&1    

Now, when the cron executes a script the contents of the log get renewed everytime. So, I want the contents to be added to the same file with time stamp of the executed time and below the contents of each time along with the existing contents. How can I do this.


Solution:1

How to get timestamp in a file

To add a time stamp in a file you can use date see man date for more details. For example if you use in terminal you will have output like,

$ date +%d-%m-%y/%H:%M:%S  19-12-13/09:14:42  

The output is in the format dd-mm-yy/hour:min:sec

If you wish to put the time stamp in a file, use

date +%d-%m-%y/%H:%M:%S > filename  

Redirection

If you use date +%d-%m-%y/%H:%M:%S > filename then the date will be stored into the file but it it will be overwritten every time you use the command. To append it in an existing file use,

date +%d-%m-%y/%H:%M:%S >> filename  

It will add the last execution output at the end of your existing file.

What you do in your case

You can add the following line at the end of your /home/backup.sh,

date +%d-%m-%y/%H:%M:%S  

And use the following in crontab,

0 0 * * * /home/backup.sh >> /home/groupz/db-backup/fbackup.log 2>&1  

I think the above modification should do what you want.


Solution:2

why not just

0 * * * * (/bin/date && /home/backup.sh) >> /var/log/backup.log 2>&1


Solution:3

You can append something to a file using two of these things '>'.

$ echo "test" >> test.txt  $ echo "test" >> test.txt    $ cat test.txt  test  test  


Solution:4

(On Debian Jessie) Use the ts command which is part of the moreutils package. E.g.:

0 0 * * * /home/backup.sh | ts '[%Y-%m-%d %H:%M:%S]' > /home/groupz/db-backup/fbackup.log 2>&1    

This will prepend the timestamp to every line of the output and save it into your log.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »