Search code examples
perlbashoutputtee

Perl STDERR printed in the wrong order with Tee


I'm trying to redirect STDOUT and STDERR from a perl script - executed from a bash script - to both screen and log file.

perlscript.pl

#!/usr/bin/perl

print "This is a standard output";
print "This is a second standard output";
print STDERR "This is an error";

bashscript.sh

#!/bin/bash

./perlscript.pl 2>&1 | tee -a logfile.log

If I execute the perlscript directly the screen output is printed in the correct order :

This is a standard output
This is a second standard output
This is an error

But when I execute the bash script the STDERR is printed first (in both screen and file) :

This is an error
This is a standard output
This is a second standard output

With a bash script as child the output is ordered flawlessly. Is it a bug with perl or tee? Am I doing something wrong?


Solution

  • An usual trick to turnoff buffering is to set the variable $|. Add the below line at beginning of your script.

    $| = 1;
    

    This would turn the buffering off. Also refer to this excellent article by MJD explaining buffering in perl. Suffering from Buffering?