How To Redirect STDERR to STDOUT in Perl

Redirecting STDERR to STDOUT in Perl:

open STDERR, '>&STDOUT';

Reassign raw file handles:

*STDERR = *STDOUT;

Redirect all output to a logfile:

open(LOG,">/tmp/foo.log");
*STDERR = *LOG;
*STDOUT = *LOG;

Example:

#!/usr/bin/perl
use strict;
use warnings;
warn "regular error";
open STDERR, '>&STDOUT';
warn "redirected error";

Output:

[kitamura@web3 perl]$ ./stderr.pl 2>/dev/null
redirected error at ./stderr.pl 6.
This entry was posted in Perl. Bookmark the permalink.

One Response to How To Redirect STDERR to STDOUT in Perl

  1. sinx says:

    Hello,

    Think about this code in context of redirecting STDOUT, STDERR:

    #!/usr/bin/perl

    use strict;
    use warnings;

    use POSIX qw(:errno_h ceil floor :sys_wait_h);

    my @run = ( ‘ls’, ‘-al’ );
    my $pid = fork();
    die “Unable to fork $!” unless defined($pid);
    if (!$pid) { # child
    open(LOG,”>”, “foo-log.log”);
    #close(STDERR);
    #close(STDOUT);
    #open STDERR, “>>&LOG”;
    #open STDOUT, “>>&LOG”;
    *STDERR = *LOG;
    *STDOUT = *LOG;
    print LOG “PRINT TO LOG\n\n”;

    exec { $run[0] } @run;
    die “Unable to execute: $!”;
    }
    waitpid($pid, WNOHANG);

    and output is shown on terminal not in log file:

    but when running this:

    #!/usr/bin/perl

    use strict;
    use warnings;

    use POSIX qw(:errno_h ceil floor :sys_wait_h);

    my @run = ( ‘ls’, ‘-al’ );
    my $pid = fork();
    die “Unable to fork $!” unless defined($pid);
    if (!$pid) { # child
    open(LOG,”>”, “foo-log.log”);
    close(STDERR);
    close(STDOUT);
    open STDERR, “>>&LOG”;
    open STDOUT, “>>&LOG”;
    #*STDERR = *LOG;
    #*STDOUT = *LOG;
    print LOG “PRINT TO LOG\n\n”;

    exec { $run[0] } @run;
    die “Unable to execute: $!”;
    }
    waitpid($pid, WNOHANG);

    Everything is ok, maybe you know why:

    *STDERR = *LOG;
    *STDOUT = *LOG;

    doesn’t work?

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>