質問

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?

役に立ちましたか?

解決

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?

他のヒント

I guess this has to do with the way STDOUT and STDERR buffers are flushed. Try

autoflush STDOUT 1;

at the beginning of your perl script so that STDOUT is flushed after each print statement.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top