Ping scripting

This is my first posting here, I haven't found exactly what I'm looking for anywhere else so I'm hoping you all can help. I have a portion of script here that needs to ping two servers, then return whether they are up or down (somehow), and then echo that information. Here is what I have so far. It does echo up/down, but the information doesn't change regardless of the ping success.

SERVERUP=1
SERVERDOWN=0
ping -q -c1 192.168.1.11 > /dev/null; ping -q -c1 192.168.1.10 > /dev/null
if [ $? -eq 1 ]
then
        SERVERUP=$((SERVERUP+1))
else
        SERVERDOWN=$((SERVERDOWN+1))
fi
 echo "Servers up: $SERVERUP Servers down: $SERVERDOWN"

Welcome to the forum.

Not quite true. It does change: 2 up, 0 down, if the last ping fails, 1 up, 1 down, if it succeeds.

There seems to be one basic misunderstanding: the $? variable represents the exit code of the last command executed; the before last's is overwritten. So your first ping 's result is lost. So, you need to evaluate it after each ping , e.g. with another if construct. Doable, but tedious and ineffective.

How about a different approach? Collect the respective exit codes, and do some math afterwards? Like

ping -c1 -W1 192.168.0.1 > /dev/null; X1=$?
ping -c1 -W1 192.168.0.1 > /dev/null; X2=$?
echo "Servers up: $((2-X1-X2)) Servers down: $((X1+X2))"

The -q is redundant if you redirect output to /dev/null . I introduced the -W timeout option to reduce execution / waiting time.

1 Like

This is perfect! Another way of looking at it certainly does the trick sometimes. I created a new servers.sh script and placed those three lines in it for testing purposes, it consistently returns correct results. It's amazing how you can go from a bunch of if statements to just three lines of code. Thank you so much for such a great response.

This is in an exec script:

ping -c 1 $othsys >>logfile.txt 2>&1

That logfile is run through sed -n -f with the following control file for sed:

# File name ping.sed
/ ping statistics / {
                    N
                   / 0 packets / {
                        s/^....br//
                        s/ .*//
                        p
                      }
                   }

In our shop other computers we ping all start with "br" that we don't need in later processing--delete that or change as necessary.