1

I am needing to ping a list of host addresses (non-sequential) and log the output as "up" or "down". I've got a start but my script seems faulty. For example. when i run the following script against a host file containing 150 hosts, i get 400+ "up" or "down" replies in the output file.

#!/usr/bin/bash
#script name: lrkdc01ping.sh
date >> /home/insight/scripts/lrkdc01ping.out
cat /home/insight/scripts/lrkdc01.txt |  while read output
do
    ping -c 1 "$output" >> /dev/null
    if [ $? -eq 0 ]; then
        echo "node is up" >> /home/insight/scripts/lrkdc01ping.out
    else
        echo "node is down" >> /home/insight/scripts/lrkdc01ping.out
    fi
done
  • 1
    Because you are appending to the file and not initializing it, I suspect that you have run the script several times, and your 400+ lines are the result of running the script repeatedly. – DopeGhoti Jun 19 '18 at 21:24
  • You should have dates in that file to easily check for what DopeGhoti suggests. – Tomasz Jun 19 '18 at 21:30
2

I would suggest something like this, which will also clear out the output file for each run rather than appending to it each time:

#!/usr/local/bin/bash
outfile="/home/insight/scripts/lrkdc01ping.out"
date > "$outfile"
while read output; do
    echo -n "$output is " >> "$outfile"
    if ping -c1 "$output" > /dev/null 2>&1; then
        echo "up" >> "$outfile"
    else
        echo "down" >> "$outfile"
    fi
done < /home/insight/scripts/lrkdc01.txt

The main differences are using > rather than >> for the invocation of date, so that you will have a clean file for each run; and simplifying your use of the exit code of ping:

It's cleaner to just

if verb; then
    action
else
    failure_action
fi

rather than

verb
if [[ 0 -eq $? ]]; then
    action
else
    failure_action
fi

Additionally, rather than having to edit four places should you decide to move or change the name of your output file, I put it into a variable so that you only need to update it in one place. My general rule of thumb is "if you're typing the same thing more than twice, it should be abstracted".

  • This seems to work. I am still, however, seeing a repeat of output start after the last ip address in the file. Somewhere in the mid of the file there is an ip address of 1.1.1.15. The repeart starts with that ip address and goes to the bottom again. Weird. – mylan Jun 20 '18 at 14:43
  • This sounds like it might be a case of GIGO - take a look at the input file and ensure the IP addresses are not repeating there. – DopeGhoti Jun 20 '18 at 14:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.