2

我试图编写基于“ps”的“服务”脚本。我的代码:

#!/usr/bin/perl
use strict;
use warnings;
die "usage:    $0 <service name>\n" unless $ARGV[0];
my $service = $ARGV[0];
open(my $ps, "ps -aux |") || die "Uknown command\n";
my @A = <$ps>;
close $ps;
foreach my $i(grep /$service/, @A){
    chomp $i;
    if($i=~ /root/){
        next
    }
    print "$i\n";
}

我的问题:针对 undef arg 运行脚本时,例如:

$0 blablabla 

如果没有出现这样的服务/当返回 0,我想返回一个输出谢谢

4

4 回答 4

2

我假设您要问的是:找不到匹配行时如何给出正确的消息?

好吧,只需将结果存储在数组中即可:

my @lines = grep { !/root/ && /$service/ } @A;

if (@lines) {   # if any lines are found
    for my $line (@lines) {
        ...
    }
} else {
    print "No match for '$service'!\n";
}

或者您可以打印匹配的数量,而不管它们的数量:

my $found = @lines;
print "Matched found: $found\n";

另请注意,您可以在 grep 中添加对 root 的检查。

作为旁注,这部分:

die "usage:    $0 <service name>\n" unless $ARGV[0];
my $service = $ARGV[0];

也许写得更好

my $service = shift;
die "usage ...." unless defined $service;

它专门检查参数是否已定义,而不是真实与否。

于 2013-03-04T17:19:28.607 回答
2

如果我理解正确,如果没有找到此类服务,您想通知用户吗?如果是这样,您可以按如下方式修改脚本:

my $printed;                        # Will be used as a flag.
foreach my $i(grep /$service/, @A){
    chomp $i;
    if($i=~ /root/){
        next
    }
    $printed = print "$i\n";        # Set the flag if the service was found.
}
warn "No service found\n" unless $printed;
于 2013-03-04T17:16:49.463 回答
1

你可以尝试这样的事情:

my @processes = grep /$service/, @A;
if ( scalar @processes ) {
    foreach my $i( @processes ){
        chomp $i;
        if($i=~ /root/){
            next;
        }
        print "$i\n";
    }
}
else {
    print 'your message';
}
于 2013-03-04T17:17:57.350 回答
0

您可以在循环grep中遍历它之前检查命令的结果,例如:for

...

my @services = grep { m/$service/ } @A;

# Filter the perl process running this script and...
if ( ! @services ) { 
    print "No service found\n";
    exit 0;
}

foreach my $i( @services ){
    ...
}

考虑到该grep命令永远不会给出错误的返回,因为它包含perl进程,所以你必须过滤它,但我希望你明白。

于 2013-03-04T17:18:16.307 回答