tags:

views:

59

answers:

3

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
+1  A: 

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
OMG_peanuts
I 'almost' thought of doing this but turned away. However, this gives me an additional option I can integrate into this script. Thanks...
XO
+7  A: 

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.

ar
Doh, just like with sed. Thanks a million.
XO
A: 

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
ghostdog74
Thanks. I agree --just use perl exclusively. I integrated this into an already written shell script that I do not care to port. This serves as a convenient, consistently fast (that is, it does not hang) one-liner.
XO