Save Cron output to a file
- 1 Min. Read.
To save the output of a Cron job to a file, you can use the following command:
1 |
0 * * * * /task.sh >> /var/log/task.log 2>&1 |
This script will execute /task.sh
every hour, and append the output to /var/log/task.log
.
What does 2>&1 mean?
- 2 refers to the second file descriptor of the process, i.e. stderr.
- > means redirect.
- &1 means the target of the redirection should be the same location as the first file descriptor, i.e. stdout.
In other words, both standard output and errors will be written to the log file specified.
Add timestamps to every line
It may come in handy to have a reference at what time each line was appended to the log file. Create a file called /date.sh
with the following contents:
1 2 3 4 5 6 |
#!/bin/bash while read x; do echo -n `date +%d/%m/%Y\ %H:%M:%S`; echo -n " "; echo $x; done |
And in crontab, modify your command like this:
1 |
0 * * * * /task.sh 2>&1 | /date.sh >> /var/log/task.log |
This will add a nice timestamp before every line that gets written to the log file.
1 2 3 4 |
08/06/2016 19:00:03 Processing files 08/06/2016 19:00:03 No new files found 08/06/2016 20:00:02 Processing files 08/06/2016 20:00:02 Adding 10 files to queue |