I have a (BASH) shell script that executes several PHP files. As they execute (over several seconds) they produce output. I am trying to capture this output from the shell script and prepend a timestamp on each line.
I am close, but need a little help.
Consider the following PHP script:
<?php
    echo("this is some output\n");
    sleep(1);
    echo("another line of output\n");
    sleep(3);   
    echo("final line of output\n\n");
?>
Running that alone produces this output:
$ php ryan.php
this is some output
another line of output
final line of output
Now consider the following shell script:
#!/bin/bash
shopt -s expand_aliases
alias date='date "+%a %d-%b-%Y %R:%S"'
alias stamp='sed "s/^/$(date)  /"'
php ryan.php | stamp
sleep 1
php ryan.php | stamp
sleep 1
exit 0
Running the following command produces the following output:
$ ./test.sh
Tue 23-Jun-2015 10:14:48  this is some output
Tue 23-Jun-2015 10:14:48  another line of output
Tue 23-Jun-2015 10:14:48  final line of output
Tue 23-Jun-2015 10:14:48
Tue 23-Jun-2015 10:14:53  this is some output
Tue 23-Jun-2015 10:14:53  another line of output
Tue 23-Jun-2015 10:14:53  final line of output
Tue 23-Jun-2015 10:14:53
As you can see, the timestamps are printing. However, they're all the same time for each line of output per PHP script execution, when instead there should be a few seconds of difference between each line of output.
I believe this is happening because the date command is evaluated only once per line in the shell script, when I would like to have it reevaluated each time there is new output from the PHP script.
Is this possible?
Update
I found the following to be my final solution:
#!/bin/bash
shopt -s expand_aliases
FMT='%a %d-%b-%Y %R:%S'
alias stamp="perl -p -MPOSIX -e 'BEGIN { $|=1 } {\$!=1} \$_ = strftime(\"$FMT  \", localtime).\$_'"
php ryan.php | stamp
sleep 1
php ryan.php | stamp
sleep 1
exit 0