Capture script output to add datetime to ouput in realtime

I'm looking to capture the output of a shell script execution in real time to enrich it with information giving the date and time.

To illustrate, I have for example a script of this type that I must not modify:

#!/bin/bash
for i in 2 3 1
do
  echo "Waiting for $i seconds ..."
  sleep $i
done

The script produces the following output:

Waiting for 2 seconds ...
Waiting for 3 seconds ...
Waiting for 1 seconds ...

I am trying to produce the output of the type:

2021-06-16 11:44:48 [INFO] Waiting for 2 seconds ...
2021-06-16 11:44:50 [INFO] Waiting for 3 seconds ...
2021-06-16 11:44:53 [INFO] Waiting for 1 seconds ...

I use the following shell functions for formatting in a script that runs my initial script:

function log {
   echo `date +%Y-%m-%d" "%H:%M:%S`" $@"
   if [ "$LOGFILE" != "" ]
   then
      echo `date +%Y-%m-%d" "%H:%M:%S`" $@" >>$LOGFILE
   fi
}

function loginf {
   log "[INFO] $@"
}

I manage very well with a while loop on a read to capture the output of my script, but I get all the lines at the same time (end of its execution) and therefore all lines have the same datetime. I try to get the lines each time the script produces a line and not at the end of the execution.


The ts command from package moreutils does precisely what you are looking for:

./script.sh | ts

It has various options for formatting the time stamp. For instance,

ts '%F %T [INFO]'

will give you the exact format you use in your question.