title: How to add timestamp while redirecting stdout to file in Bash?
body: <p>I have a program (server) and I am looking for a way (script) that will redirect (or better duplicate) all its <code>stdout</code> to file and add timestamp for each entry.</p>
  
  <p>I've done some research and the furthest I could get was thanks to <a href="https://stackoverflow.com/questions/1507674/how-to-add-timestamp-to-stderr-redirection">How to add timestamp to STDERR redirection</a>. It redirects <code>stdout</code> but the timestamp added is of the time when the script finishes:</p>
  
  <pre><code>#!/bin/bash
  ./server | ./predate.sh &gt; log.txt
  </code></pre>
  
  <p>code of <code>predate.sh</code>:</p>
  
  <pre><code>#!/bin/bash
  while read line ; do
      echo "$(date): ${line}"
  done
  </code></pre>
  
  <p>It seems that server output is flushed after exit of the program.(without redirecting it works fine). Also if I try using <code>predate.sh</code> on given example in mentioned thread, it works perfectly. I am aware it would be easy adding a timestamp to the main program but I would rather avoid editing its code.</p>