试图让Perl脚本正确计算来自grep进程的结果数

时间:2016-07-18 22:44:38

标签: perl grep

所有

我正在尝试grep一个特定的进程,该进程在其输出中包含列出的路径(显示在我的@t_processes数组中)。计数将始终为1,因为您用于grep的命令也将默认显示在输出中。因此,如果计数大于1,我正在使用它确实在运行。当我grep它们时,所有这些进程都会启动,并且命令行中至少会有两个结果返回。但是当我运行脚本时,我只返回打印语句:"进程$ t_process匹配!它在运行吗?...."。任何人都可以提供一些指导吗?

use strict;
use warnings;


sub main
{

my @t_processes = (
'/hosting/configs/tomcat7/prod-06_fc' ,
'/hosting/configs/tomcat7/prod-07_fc',
'/hosting/configs/tomcat7/prod-07',
'/hosting/configs/apache22/prod-06_fc/',
'/hosting/configs/jboss6/jb-prod-06'
);

foreach
    my $t_process(@t_processes)
{
    my $match_count = 0;
    if(`ps -aef | grep -i $t_process`) 
    {

        print "Process $t_process is matched! Is it running?....";
        if($match_count > 1)
            {
                print "The process is running\n ";
            }   
        else
            {
                $match_count++
            }                           

    }
    else 
    {
        print "The process $t_process is not running, please start it!\n" ;
    }


}

}


main();

2 个答案:

答案 0 :(得分:1)

你的grep if条件总是成功,因为grep本身产生一个结果,因此始终满足if条件。

尝试运行

if(`ps -aef | grep -i $t_process | grep -v grep`)

答案 1 :(得分:1)

正如我在你的OP评论中所说,你的$match_count逻辑存在致命缺陷。首先,在for()循环内声明它,它将在每个进程上将其重置为零。其次,除了else()语句之后,你永远不会分配给它;到那时,你即将脱离循环。

这是一个更简单的方法:

use strict;
use warnings;

my @t_processes = qw(nginx blah);

for my $t_process(@t_processes){
    if(`ps -aef | grep -i $t_process | grep -v grep`){
        print "$t_process is running\n";
        next;
    }
    print "$t_process is not running, please start it!\n" ;
}

输出:

nginx is running
blah is not running, please start it!