in reply to Error trapping while capturing stdout

under unix shell 2>&1 redirects STDERR to STDOUT. If you then add a pipe you do indeed get the whole lot going down the pipe (so if this pipe then connected to a perl file handle you would be reading STDERR and STDOUT mixed together in Perl). Perl sends it's warnings to STDERR as this little test shows

# A simple perl script to generate a warning : perl -we 'my $t; my $t' "my" variable $t masks earlier declaration in same scope at -e line 1. # the same with STDOUT redirected to null : perl -we 'my $t; my $t' >/dev/null "my" variable $t masks earlier declaration in same scope at -e line 1. # same with STDERR to null, aaah the sound of silence : perl -we 'my $t; my $t' 2>/dev/null :
What may be enough for you is to check the exit code of the script you call (hopefuly it exits with 0 when it runs OK and non-zero values for failures
my $cmd="ls /no/way"; my @data=`$cmd`; if($?) { print "$cmd failed with exit code $?\n"; exit 1 } foreach (@data) { chomp; my @ret=split; # do something with @ret here ? }

This is running the external script to completion first then checking it did not give an error code before going on to process the results.

Cheers,
R.

Replies are listed 'Best First'.
Re^2: Error trapping while capturing stdout
by ccarden (Monk) on Sep 14, 2004 at 15:35 UTC
    Thanks for confirming my understanding of 2>&1|.

    Now you got me thinking, with your second point. The called script does, indeed exit with a code. How would perl -w affect that? If perl gives warnings, it doesn't change the script's exit code. So I could still get an exit code of 0, but with warnings from the interpreter.

    Another unwanted behavior that wasn't trapped was perl exiting with a "bad interpreter" message. I tracked it down to hidden carriage returns (thanks to vi's [dos] message), but the calling script should have caught that. I'll test your suggestion for trapping.

    Thanks.

      You would still get the warnings if you redeirected STDERR to STDOUT but if you trust the called script to exit non-zero when it fails then you no longer need to examine STDERR. You can throw it away with 2>&/dev/null and just test the exit value from the script.

      Fixing the warnings may also help ;-)

      The bad interpreter error would also return a non-zero value to the calling script and get caught in the $? test.

      Cheers,
      R.