I want to echo a message in case a system is reachable by ping or echo a different message in case it's not reachable.
Sample code i wrote is
ping localhost -n 2 | grep 'ttl' > ping_op; ls ping_op > /dev/null && drReachable=Alive; echo -e `date`: \\t "DR server is reachable" >> dr_check.log
i thought if the grep command finds ttl only then it will create a file but it does not seem like that.
How can i achieve conditional execution for the same
i thought i will o/p the command to a file and do a line count but it is fine for hpux but it doesn't work for solaris, which outputs a single line, not reachable or alive.
I'm new to this stuff. maybe there are better approaches
&& will only check if the last exit code was true/0 and checking if redirecting to a ls to a file was successful is not helpful.
Afaik you can't implement a "else" conditions by this.
Example:
VAR=somehost
ping -c3 $VAR > /dev/null 2>&1
if [ $? != 0 ]; then
echo "`date` -- Host $VAR can't be reached!"
else
echo "`date` -- Host "$VAR is reachable."
fi
If you write something like ping/network monitoring script (maybe run via cron?), I suggest you leave out the ok message since this would produce tons of useless output. In this case you do not need a else-condition and could do something like
I also recommend in this case, using something like a lock-file that is being touched in the beginning and deleted in the end of the script to ensure that this script does not run multiple instances in parallel.
PL=`ping -c 10 localhost|grep "% packet"|cut -d"%" -f1|awk '{print $6}'`
if [ $PL -gt 50 ]
then
echo `date` "-> DR server is unreachable $PL percent package loss"
fi
echo `date` "-> DR server is reachable $PL percent package loss"