5

A bash script is run from cron, stderr is redirected to a logfile, this all works fine. The code is:

*/10 5-22 * * * /opt/scripts/sql_fetch 2>> /opt/scripts/logfile.txt

I want to prepend the date to every line in the log file, this does not work, the code is:

*/10 5-22 * * * /opt/scripts/sql_fetch 2>> ( /opt/scripts/predate.sh >> /opt/scripts/logfile.txt )

The predate.sh script looks as follows:

#!/bin/bash
while read line ; do
    echo "$(date): ${line}"
done

So the second bit of code doesn't work, could someone shed some light? Thanks.

kingmilo
  • 147
  • 2
  • 11
  • Just FYI for those reading this, there was a problem with cron on my system and that is why I was not getting results, the above code does in fact work, however the solution posted directly below from Ryan is much better. – kingmilo Aug 22 '11 at 10:04

2 Answers2

10

I have a small script cronlog.sh to do this. The script code

#!/bin/sh
echo "[`date`] Start executing $1"
$@ 2>&1 | sed -e "s/\(.*\)/[`date`] \1/"
echo "[`date`] End executing $1"

Then you could do

cronlog.sh /opt/scripts/sql_fetch >> your_log_file

Example result

cronlog.sh echo 'hello world!'

[Mon Aug 22 04:46:03 CDT 2011] Start executing echo
[Mon Aug 22 04:46:03 CDT 2011] helloworld!
[Mon Aug 22 04:46:03 CDT 2011] End executing echo
Ryan Ye
  • 3,159
  • 1
  • 22
  • 26
  • 1
    This is great, but it looks like it will print the same timestamp for every line, even if your script is outputting lines of text for several minutes. Instead of `sed`, you can try piping the output to `ts` and it should have a different timestamp on each line. `ts` comes from the moreutils package, see this related question: https://stackoverflow.com/questions/21564/is-there-a-unix-utility-to-prepend-timestamps-to-stdin – DMack Apr 10 '19 at 22:40
1
*/10 5-22 * * * (/opt/scripts/predate.sh; /opt/scripts/sql_fetch 2>&1) >> /opt/scripts/logfile.txt

should be exactly your way.

glglgl
  • 89,107
  • 13
  • 149
  • 217