in reply to Both print and redirect STDOUT and STDERR
Add 2>&1 | tee out.txt to your command (or equivalent in the script).
You'll get better results if you use $| = 1; in the script, but it's not necessary to fulfill your requirements.