georgetovrea
georgetovrea

Reputation: 577

how to return results from shell script to perl?

I try to get rtt results (like 149.982/150.125/150.280/0.265 ms ) from shell script in perl , now the ping.sh can retrive the rtt results from shell script ,but how to return the results and how to get the return results from shell script in perl ?

call.pl

my $answer= system (".  /home/george/ping.sh;getrtt  8.8.8.8");
if($answer == 0)
{
    exit($answer >> 8);
    my $results =  ##how to get the rtt results from ping.sh ???


 }

ping.sh

getrtt()
{
   if  ping $ip -c 5 -t 5 | grep -oP '[+-]?([0-9]*[.])?[0-9]+\/[+-]?([0-9]*[.])?[0-9]+\/[+-]?([0-9]*[.])?[0-9]+\/[+-]?([0-9]*[.])?[0-9]+ ms'
   then
      echo ##how to retrun the results (ping $ip -c 5 -t 5 | grep -oP '[+-]?([0-9]*[.])?[0-9]+\/[+-]?([0-9]*[.])?[0-9]+\/[+-]?([0-9]*[.])?[0-9]+\/[+-]?([0-9]*[.])?[0-9]+ ms')???
   else
      echo '1'
 fi 
 }

Upvotes: 0

Views: 144

Answers (1)

within the shell function :

  1. you can use the $() syntax to get the result of the ping in a variable
  2. you can echo the result

within the perl program : you can open a pipe | and read out the shell stdout

file ping.sh:

getrtt()
{
   ip=$1;
   if result=$(ping $ip -c 5 -t 5 | grep -P 'ms$')
   then
      echo $result
   else
      echo '1'
 fi
 }

file graboutput.pl:

#!/usr/bin/perl

local *EXEC; open EXEC,'. ./ping.sh && getrtt 8.8.8.8|' or die $!;
while (<EXEC>) {
 # do something with the result
 print;
}
close EXEC;

exit $?;

1; # $Source: /my/perlscritps/graboutput.pl$

Note: the ping on my linux box doesn't have the same format i.e. : 5 packets transmitted, 0 received, +5 errors, 100% packet loss, time 4005ms so I changed the -oP option of the grep w/i ping.sh

Upvotes: 1

Related Questions