# Add datetime to STDOUT and STDERR redirected values



## dragonbite (Dec 14, 2012)

I have a script that is run by a CRON job and the output goes into a log file I have set up. Unfortunately it only grabs the STDOUT and STDERR messages.


```
30 5 * * * $HOME/updatedb.sh 1>2 2>>/var/log/companyname/username/updatedb.sh.log
```

Is there a way to add or concatenate the datetime in front of the STD* messages?


----------



## SirDice (Dec 14, 2012)

Why don't you simply add the date(1) command to updatedb.sh?


----------



## dragonbite (Dec 14, 2012)

SirDice said:
			
		

> Why don't you simply add the date(1) command to updatedb.sh?



I do not understand what you mean or where you are suggesting to include it.

Normally the script produces no STDOUT or STDERR output and so nothing goes into the log file and CRON does not send me an email.

It is only if there is an output that is captures, placed in the log file and emailed by CRON.  This is where I hope to concatenate the date value right before it but if there there is no message I do not want to output anything.


----------



## SirDice (Dec 14, 2012)

I don't think there's an easy way to do this. You'd have to rewrite the script to check for any errors and if there are print the date plus the rest of the output.


----------



## dragonbite (Dec 14, 2012)

I came up with something, but cannot quite capture the date.  It would put a line, supposedly with the date in the beginning, into the log file without triggering CRON to send an email.

In CRONTAB

```
30 5 * * * echo "$(date +"%Y-%m-%d %T") Started; /$HOME/updatedb.sh 1>&2 2>>/var/log/companyname/username/updatedb.sh.log
```

I have tried a couple ways to get the current date value but I have not been able to get it.  At this point I don't even care of it is formatted, though if I could get it formatted that would be great.

If I can get this to work then at least in the log file it will tell me when the errors happened.

I did just have all of the errors go into a file and echo out the contents into a log file but that whole process was rejected by the system administrator who wants to see the system tools utilized more than custom scripting.


----------



## dragonbite (Dec 14, 2012)

Ok, sort of solved.  I needed to add an escape character before the values.


```
LOGFILE=/var/log/companyname/username/updatedb.sh.log
*/5 * * * * echo "$(date +'\%Y-\%m-\%d \%T') Started." >> $LOGFILE; /$HOME/updatedb.sh 1>&2 2>>$LOGFILE
```

So it echoes, for example, "2012-12-14 11:25:00 Started." into the log file and does not trigger CRON to send me an email.  If there is an error, it will show up right below the date and time and will send me an email of just the message.


----------

