Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: capturing stderr of echo piped to a file

by Crackers2 (Parson)
on Oct 28, 2014 at 22:10 UTC ( [id://1105381]=note: print w/replies, xml ) Need Help??


in reply to capturing stderr of echo piped to a file

Your redirection is in the wrong order:

my $command = "echo $writeline >> $file"; my $output = `$command 2>&1`;

Writing that out, you end up with

my $output = `$command echo $writeline >> $file 2>&1`;

Which means redirect STDOUT to the file, then STDERR to (current) STDOUT, i.e. also to the file. You probably want

my $output = `$command echo $writeline 2>&1 >> $file`;

instead, i.e. redirect STDERR to STDOUT, then STDOUT (but not the redirected STDERR) to the file.

Replies are listed 'Best First'.
Re^2: capturing stderr of echo piped to a file
by boftx (Deacon) on Oct 29, 2014 at 18:58 UTC

    Your statement is simply not true. The order of the redirects doesn't matter and in my experience having 2>&1 at the end of the line is much more common. A simple test on the command line with a perl script that issues a warn as well as a print statement will demonstrate this.

    You must always remember that the primary goal is to drain the swamp even when you are hip-deep in alligators.

      Perhaps you should just try it?

      > { echo out; echo err >&2; } >f1 2>&1 > cat f1 out err > { echo out; echo err >&2; } 2>&1 >f1 err > cat f1 out

      Redirection order definitely DOES matter in the shell. (Hmm, unless it's shell-specific? I'm using bash)

      And just to do exactly what you said..

      > perl -e'print "print\n"; warn "warn"' >f1 2>&1 > cat f1 warn at -e line 1. print > perl -e'print "print\n"; warn "warn"' 2>&1 >f1 warn at -e line 1. > cat f1 print

      In the first case both print and warn go to the file, in the second case warn goes to stdout and print to the file.

        ~/stuff > perl foobar.pl Normal STDOUT Going to STDERR ~/stuff > echo 'Just a starting point > ' >JGBtest.txt ~/stuff > cat JGBtest.txt Just a starting point ~/stuff > perl foobar.pl >>JGBtest.txt 2>&1 ~/stuff > cat JGBtest.txt Just a starting point Going to STDERR Normal STDOUT ~/stuff > cat foobar.pl #!/usr/bin/perl use warnings; use strict; print "Normal STDOUT\n"; warn "Going to STDERR\n"; exit; __END__ ~/stuff >
        You must always remember that the primary goal is to drain the swamp even when you are hip-deep in alligators.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1105381]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (7)
As of 2024-04-19 07:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found