返回多个退出代码的 Perl 脚本

返回多个退出代码的 Perl 脚本

我有一个 Perl 脚本,它在里面执行另一个 Perl 脚本:

#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long qw(:config no_ignore_case bundling_override);
no warnings 'uninitialized';
#print '<<<check_jenkins_jobs>>>';
my ($port, $host) ;
# Parse command line arguments
GetOptions ('host=s'   => \$host, 'port=s' => \$port);
if( (!defined($host)) || (!defined($port))) {
        print "USAGE:perl $0 -host mbiradar2d -port 8080";
    exit 1;
}
use constant {
    OK => 0,
    WARNING => 1,
    CRITICAL => 2,
    UNKNOWN => 3,
};
my @output = `perl "H:\\Mangesh\\check_jenkins_jobs.pl" -host $host -port $port`;
my $line;
my $status;
my $statustxt;
foreach $line (@output) {
    #print $line;
    my @values = split('~', $line);
    if($values[0] =~ /^CRITICAL/) {
        $status = 2;
        $statustxt = 'CRITICAL';
        print "$values[0] : $values[1] has health score $values[2]";
        exit CRITICAL;
    }
    elsif($values[0] =~ /^WARNING/) {
        $status = 1;
        $statustxt = 'WARNING';
        print "$values[0] : $values[1] has health score $values[2]";
        exit WARNING;
    }
    else {
        $status = 0;
        $statustxt = 'OK';
        print "$values[0] : $values[1] has health score $values[2]";
        exit OK;
    }
}

下面是我在上面脚本中解析以供进一步使用的内部 Perl 脚本的输出:

CRITICAL ~ First_run ~ Build stability: 3 out of the last 4 builds failed. ~ 25
CRITICAL ~ Mangesh_Testing ~ Build stability: All recent builds failed. ~ 0
CRITICAL ~ MKS_Integrity ~ Build stability: All recent builds failed. ~ 0
OK ~ MKS_TEST ~ Build stability: No recent builds failed. ~ 100
CRITICAL ~ Rest_api_testing ~  ~ no score
CRITICAL ~ Second_job ~  ~ no score
OK ~ Team_test ~ Build stability: No recent builds failed. ~ 100
OK ~ test ~ Build stability: No recent builds failed. ~ 100
CRITICAL ~ TEST_1 ~ Build stability: 2 out of the last 3 builds failed. ~ 33
OK ~ Update_Outlook ~ Build stability: No recent builds failed. ~ 100

但问题是,这个脚本在打印完第一行内部 Perl 脚本输出后就退出了。我想在打印完每一行输出后退出这个脚本。我还有什么其他方法可以实现这一点?如果这个脚本根据 Nagios 兼容输出退出,那就更好了。例如,0 表示 OK,1 表示 WARNING,2 表示 CRITICAL,3 表示 UNKNOWN

答案1

您正在告诉脚本exit在第一行之后执行块exit中的每个语句if

如果您希望脚本的逻辑保持不变但想要打印所有内容,请让它在处理和退出之前在单独的循环中打印输出。

foreach $line (@output)  {
   print $line;
}

相关内容