Question:

How to get the result of cmd1 in Perl?

by  |  earlier

0 LIKES UnLike

Hi expertise,

Could you let me know how to get the result of each command in Perl during using system command?

Ex:

#!/bin/perl

...

$rs=system("cmd1 | cmd2 | tee -a text.txt");

...

In this example, Perl return the exit code of only the last command.

Please let me know how can I get the exit code for each command in this case?

Regards,

James

 Tags:

   Report

2 ANSWERS


  1. To start with, for the masses, Joe's answer is incorrect - system will never 'return' a string and clearly this business with concatenating a set of system invocations does not reproduce a set of piped processes.  Nice try Joe.

    I would point you at 'perldoc -f system'  

    The problem you are facing is a symptom of the more generic problem of using a chain of pipes and trying to capture the exit codes of each process.

    As I see it you have a number of options if you do indeed require exit codes:

    i) Have you considered using a temporary file to track this:

    my $finalRc = system("(cmd1; $?>/tmp/cmd1)|(cmd2;$?>/tmp/cmd2)|tee -a text.txt");

    my $rcCmd1 = `cat /tmp/cmd1`;

    my $rcCmd2 = `cat /tmp/cmd2`;

    ** Warning though: this method will miss cases where you may want to identify if a process segfaulted, etc**  It is however richer than your previous attempt in that it will give you the granular exit codes.

    2) You can have a wrapper script which redirects the exit codes to a file and does whatever processing you may wish to have done on the individual exit codes.

    ie.

    wrapper.pl:  ...my $rc= system($ARGV[0]); if ($rc ==-1) { warn('failed to exec'; } elsif ($rc...

    And then in your parent:

    system ("wrapper.pl cmd1 | wrapper.pl cmd2 | .....

    My first suggestion is the more generic solution, however 2 might prove more effective and functional depending on what you're trying to achieve.

      


  2. What you have won't work because you call system() one time and string the three commands to it. The only thin returned will be the last, because you have piped the other command return values to the next command.

    If cmd1 and cmd2 return strings, you can cat the results together:

    $rs = (system("cmd1")) . ' ' . (system("cmd2")) . ' ' . (system("tee -a text.txt"));

    The ' ' between each command is a space to keep the results separated. Add the dots, with spaces around them.

    There are lots of other way, but if you're getting strings back, this will work. Even returned numbers should work, because perl will see that your cat'ting things together and will treat each one as a string value for the assignment.

Question Stats

Latest activity: earlier.
This question has 2 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.