Ping Host Until it is up and email

Hi I am trying to write a script which runs until the host is up. i got it figured out that it needs to be in loop till it return $? = 0.

Not getting it through though. I am not sure about the 6th line !!!

#!/bin/sh
HOSTS="host.txt"
ping(){
for myhost in "$HOSTS"
do
ping -c -1 "$myhost" && $? -eq 0
done
exit
}

if ping $HOSTS
then
echo "server up" |mail -s "server up" xxx@ABC.com
echo "server up"
fi

To keep the forums high quality for all users, please take the time to format your posts correctly.

First of all, use Code Tags when you post any code or data samples so others can easily read your code. You can easily do this by highlighting your code and then clicking on the # in the editing menu. (You can also type code tags

```text
 and 
```

by hand.)

Second, avoid adding color or different fonts and font size to your posts. Selective use of color to highlight a single word or phrase can be useful at times, but using color, in general, makes the forums harder to read, especially bright colors like red.

Third, be careful when you cut-and-paste, edit any odd characters and make sure all links are working property.

Thank You.

The UNIX and Linux Forums

I think you have the loop in the wrong place. You don't want to ping ALL the hosts before you email, do you?

You also don't want to call your function the same thing as an external command, that could infinite-loop or worse.

I don't think you need a function here anyway.

This will work with linux ping but not other pings, which don't all return a value properly.

for H in $HOSTS
do
        while ! ping -c 1 $H > /dev/null 2> /dev/null
        do
                true
        done

        echo "$H is up"
done
1 Like

Also if you want to read the host.txt file into the HOSTS variable use:

HOSTS=$(cat hosts.txt)

before the Corona688's for loop

or start the for loop with

for H in $(cat hosts.txt)

Thanks alot guys.. BUt i got into another lock now.

When i use the host file for multiple host, the script waits until the first host is up to execute the other ipaddress..

The case here is , i have 10 ipadreses and i want to know whenever the systems comes up..

 
#!/bin/sh
HOSTS="host.txt"
while read host
do
        ping $host -n 1 $H 1>/dev/null && echo "$host is up"
done < $HOSTS

Useless Use of Cat Award

while read host
...
done < inputfile

It still hungs up if the first host is down.

Try this:

HOSTS=$(cat hosts.txt)
while [ -n "$HOSTS" ]
do
    NEW=
    for H in $HOSTS
    do
        if ping -c 2 $H 2>&1 | grep -iq "[^0-9]0%.*loss"
        then
            echo "Server $H up" | mail -s "server up" xxx@ABC.com
        else
            NEW=$NEW" "$H
        fi
    done
    HOSTS=$NEW
done
1 Like