Pinging Multiple Hosts
- 0
- Add a Comment
- No Related Post
Pinging Multiple Hosts
Over the past few issues of Penguin Shell, I’ve been sharing some shell scripts that get things done quickly and efficiently. The response has been so good that I thought I’d share another today.
Everyone is aware of ping, the program for checking the connection to a connected computer. Today’s shell script gives you the ability to ping several hosts simultaneously, using keyboard input.
Let’s look at the script:
#!/bin/sh
# set the external host name with keyboard input
out_host=$1
# ping the localhost
ping -c 2 localhost
if [ $? != 0 ]; then
echo “br>
fi
#ping the external host
ping -c 2 $out_host
if [ $? != 0 ]; then
echo “Couldn’t ping an external host.”
fi
#return a process id
echo “The pid of this process is $$”
This script does only a few things, but does them quite well. First, it looks for input from the keyboard in the form of the out_host=$1 line. This sets the out_host variable with the character string returned from the keyboard.
Next, the script executes the ping command with the -c 2 option (count, 2 - or ping twice). The first ping command is executed on the localhost - IP 127.0.0.1. If the results of the ping command are empty (if [ $? != 0 ];), the program echoes to the screen the line, “Couldn’t ping localhost.” and moves on to the next section.
The second ping command is executed on the host you’ve input when calling the script. In other words, you’ll execute the script with the command:
hostping.sh www.yahoo.com
The script will grab the “www.yahoo.com” string from the keyboard input and use it when executing the ping command in the second block. If there’s no response from www.yahoo.com (if [ $? != 0 ];), the program will echo to the screen the line, “Couldn’t ping an external host.”
Finally, as much for fun as anything else, the script returns the process id assigned at the time the script was executed.
