How to add the logs to a crontab with time stamp
Solution 1
why not just
0 * * * * (/bin/date && /home/backup.sh) >> /var/log/backup.log 2>&1
Solution 2
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 3
(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.
Related videos on Youtube
user3004356
Updated on September 18, 2022Comments
-
user3004356 over 1 year
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.
-
Vylmarion almost 5 yearsDon't forget to escape the "%" character in your crontab!
+%d-%m-%y/%H:%M:%S
Would become :+\%d-\%m-\%y/\%H:\%M:\%S
-
-
user3004356 over 10 yearsWhat about timestamp
-
Dominik over 7 yearsThis should be the accepted answer
-
Hamman Samuel about 7 yearsDidn't work for me, I'm using Ubuntu 16.04. I installed
moreutils
-
Stephen Rauch almost 6 yearsIsn't
echo `date -u`
the same asdata -u
? -
pbhj almost 6 yearsThe echo adds a line break AIUI.