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.
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
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.