【问题标题】:how to return results from shell script to perl?如何将结果从 shell 脚本返回到 perl?
【发布时间】:2020-04-30 21:37:35
【问题描述】:

我尝试从 perl 中的 shell 脚本获取 rtt 结果(如 149.982/150.125/150.280/0.265 ms ), 现在 ping.sh 可以从 shell 脚本中检索 rtt 结果,但是如何返回结果以及如何在 perl 中从 shell 脚本中获取返回结果?

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 
 }

【问题讨论】:

  • system 不返回输出,而是成功/失败。你需要qx(“反引号”),或者“管道打开”,或者——最好的——几个好的模块之一——比如Capture::TinyIPC::System::SimpleIPC::Run3IPC::Run。你能搜索一下 Stackoverflow 吗?这已经讨论了很多次
  • 另外,您能否查看在previous question 的评论中给出的链接——this page 回答了具体问题(关于使用 shell 脚本中定义的函数)

标签: shell perl


【解决方案1】:

在shell函数内:

  1. 您可以使用$() 语法在变量中获取 ping 的结果
  2. 您可以回显结果

在 perl 程序中: 你可以打开一个管道| 并读出shell标准输出

文件 ping.sh:

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

文件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$

注意:我的 linux 机器上的 ping 格式不同 即:5 packets transmitted, 0 received, +5 errors, 100% packet loss, time 4005ms 所以我改变了 grep w/i ping.sh 的 -oP 选项

【讨论】:

    猜你喜欢
    • 2022-01-12
    • 2012-08-29
    • 1970-01-01
    • 2011-02-17
    • 2013-07-16
    • 2016-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多