0

I am doing some bash scripting and would like to know how to recognize empty output or a specific string output when running a command in the bash script.

Example - If I perform a ping to google.com and due to no connectivity I get the message "No route to host", I would like the program to echo "You have done a boo boo".

What I have tried:

if [[ "$(ping -c 1 -n -q $address | grep -q 'ping: sendto: No route to 
host')" > /dev/null ]]; 
then echo " Your server is up and working, please proceed to the next 
step"
elif [-n "$(ping -c 1 -n -q $address | grep -q 'ping: sendto: No route 
to host')" == *java* ];
then echo "Your server is down, please fix this issue"
else 
echo "No response"
fi

Also, looked at other methods of achieving this but couldn't find a working solution.

codeforester
  • 39,467
  • 16
  • 112
  • 140

1 Answers1

0

You can check the exit status of grep. grep exits 0 if it has a match.

if ! ping -c 1 -n -q $address 2>&1 | grep -q 'ping: sendto: No route to host' > /dev/null
then
    echo " Your server is up and working, please proceed to the next step"
fi
Tripp Kinetics
  • 5,178
  • 2
  • 23
  • 37
  • (Also, grepping for an error message is innately fault-prone when that error message is coming from a translation table written for humans. You don't know which locale someone will be running your script in -- if your `No route to host` in printed in anything but English, this `grep` won't catch it). – Charles Duffy Apr 03 '18 at 18:06
  • btw, you still have a stray `)"` left over from the OP's original code. – Charles Duffy Apr 03 '18 at 18:08
  • I would normally check for the exit code of `ping` itself, but I think it's not specific enough. – Tripp Kinetics Apr 03 '18 at 18:10
  • 1
    Agreed, it's not -- that's why the better approach is to use a different tool to just test the routing table, rather than to try to abuse `ping` for the purpose. `iproute2` has a subcommand that's specifically intended for the task at hand. – Charles Duffy Apr 03 '18 at 18:10