Noame has asked for the wisdom of the Perl Monks concerning the following question:

Hi,
How can i check the return codes from the example below:
system ("$cmd | tee -a $LogFile")
i want to check the output from 'tee' command and from '$cmd' command.
'$cmd' can be any unix command or other script...
Thanks.

Replies are listed 'Best First'.
Re: Check system return codes
by Corion (Patriarch) on Jun 23, 2008 at 12:22 UTC
Re: Check system return codes
by Fletch (Bishop) on Jun 23, 2008 at 12:40 UTC

    IPC::Run will also let you check piecewise parts of a long pipe chain. But if you really just want tee's functionality you can trivially re-implement it in Perl yourself (open a pipe from $cmd, write output to your output file and STDOUT, return the exit status you get when you close the pipe).

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Re: Check system return codes
by moritz (Cardinal) on Jun 23, 2008 at 12:24 UTC
    You can check the return value of system, but that's the (mangled) return value from tee, not from $cmd.

    If you want to process the output (rather then the return value), either use qx{$cmd | tee -a $logFile} or open to open a pipe and read from that pipe.

Re: Check system return codes
by cdarke (Prior) on Jun 23, 2008 at 15:35 UTC
    Since you are using the system command to execute these programs then the pipe is managed by a shell, so to get the return code (other than the last one) you need a shell solution.

    If you use Bash then you can access the pipe return code using the array PIPESTATUS, recent Korn shell version support one called 'pipefail'.

    You would probably be better managing the pipe yourself in Perl through open, and you will find that you don't need tee(1).

      If you use Bash then you can access the pipe return code using the array PIPESTATUS, recent Korn shell version support one called 'pipefail'
      With enough /bin/sh file descriptor fu, this can even be done using an ancient Bourne shell, as demonstrated by Tom Christiansen in a famous 1996 post, Csh Programming Considered Harmful. For example:
      exec 3>&1 rc=`(($SOME_COMMAND 2>&1 3>&- 4>&-;echo $? 1>&4) | tee -a $LogFile 1>& +3 3>&- 4>&-) 4>&1` exec 3>&- # $rc has the return code of $SOME_COMMAND.
Re: Check system return codes
by jettero (Monsignor) on Jun 23, 2008 at 12:36 UTC
    Try out IPC::System::Simple. You don't really need it to check the return codes, but it'll make it more chic and probably easier.

    -Paul