Conditional execution

Hi All,

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 :frowning:

You don't need to grep as the ping command returns an error status when target is unreachable.

ping localhost -n 2 && { drReachable=Alive; echo -e "$(date): \\t DR server is reachable" >> dr_check.log; }

Whithout brackets, the command after the last semicolon would run in any case.

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

#!/bin/bash

VAR=somehost
LOG=somelogfile

ping -c3 $VAR > /dev/null 2>&1 || echo `date` '-- Host $VAR cant be reached!' >> $LOG

exit 0

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.

will update you both in some time.
Will check out both the options. :slight_smile:

you can try this :slight_smile:

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"

I was using cygwin so it came to $7
i do not have access to the actual solaris server so have to check it.
Thanks a lot for the reply :slight_smile:

---------- Post updated at 08:52 AM ---------- Previous update was at 08:30 AM ----------

Thanks a lot for the input guys
used something similar to

#!/bin/bash

VAR=somehost
LOG=somelogfile

ping -c3 $VAR > /dev/null 2>&1 || echo `date` '-- Host $VAR cant be reached!' >> $LOG

exit 0