On my CentOS I am trying to execute a php script that contains an endless loop to do some fancy stuff inside. It doesn't matter that an endless loop may not be an accurate solution for most cases, but it is for my testcase. If an error occures within this loop, the error is written to an output file (as is everything from stdout). This is what I do at the moment.

exec php testfile.php >> output.log 2>&1

This works as expected, but I want to know when stdout or stderr is writing something to the file, so I need some kind of timestamp on each line.

I already tried something like this, but if I do it as mentioned there, there is simply no output at all (I suspect it's because of not being a simple shell script).

Is it possible to redirect every echo from testfile.php and every error from stderr to output.log with a timestamp on each line?


1 Answer 1


You can prefix each line with a formatted datetime string using gnu awk. However buffering can cause some lines to be reordered or the last couple of them to disappear. To avoid this, using stdbuf is recommended.

stdbuf -i0 -o0 php testfile.php  2>&1 | gawk '{print strftime("%Y%m%d-%H%M%S"), $0}' >> output.log 
  • This does seem to work, if the testfile.php only contains something like echo "Test";. But nothing is written to the output file if this echo is within the mentioned infinite loop. Could it be that because of this loop and the execution never finishes, no output is written? Mar 17, 2016 at 15:13
  • No output, maybe. I checked it now with infinite echo, and looks good.
    – user556625
    Mar 17, 2016 at 15:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .