Trying to integrate the following Perl one-liner into a shell script. This code works within a Perl script but not as a one-liner executed from a shell script.
I've tried replacing $host
with a real hostname with no luck.
#!/bin/ksh
hosts="host1 host2 host3"
PERL=/usr/bin/perl
# Check to see if hosts are accessible.
for host in $hosts
do
#echo $host
$PERL -e 'use Net::Ping; $timeout=5; $p=Net::Ping->new("icmp", $timeout) or die bye ; print "$host is alive \n" if $p->ping($host); $p->close;'
done
The single quotes in the shell stop the $host from being interpreted. So you can just stop and restart the single quotes as required:
perl -MNet::Ping -e 'if (Net::Ping->new("icmp", 5)->ping("'$host'")) {print "'$host' is alive\n"}'
Alternatively, you can pass the host in as a parameter - see the other answer.
Try to replace $host
:
$PERL -e 'use Net::Ping; $timeout=5; $p=Net::Ping->new("icmp", $timeout) or die bye ; print "$host is alive \n" if $p->ping($host); $p->close;'
with $ARGV[0]
, the first command line argument:
$PERL -e 'use Net::Ping; $timeout=5; $p=Net::Ping->new("icmp", $timeout) or die bye ; print "$ARGV[0] is alive \n" if $p->ping($ARGV[0]); $p->close;' $host
If you want to use Perl, then use the Perl interpreter to run your script.
#!/usr/bin/env perl -w
use Net::Ping;
$timeout=5;
$p=Net::Ping->new("icmp", $timeout) or die bye ;
@hosts=qw/localhost 10.10.10.10/;
foreach my $host (@hosts) {
print "$host is alive \n" if $p->ping($host);
}
$p->close;
Otherwise, you might as well use the ping
command directly from the shell
#!/bin/bash
for hosts in host1 host2 host3
do
if ping ...... "$hosts" >/dev/null ;then
.....
fi
done
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With