Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

zsh If help: if ping unsuccessful

I want to run a script if I'm connected to the internet. The way I figure is I crontab something to run every 5 minutes or something, it tries a ping to a webserver, if it is unsuccessful then it runs a command, if it's successful, I want it to end the script.

Pseudo-code:

#!/bin/zsh
if ping IP is unsuccessful
  echo test
end
like image 454
James Avatar asked Sep 05 '25 03:09

James


1 Answers

ping sets the exit status depending on its success. So you could do something like:

#!/bin/zsh
ping -c 1 myhost        # -c pings using one packet only
if [ $? -ne 0 ]; then
   echo "test"
fi

Note that commands will set their exit status ($?) by convention to be non-zero if they suffer an error.

Another version of the above would be:

#!/bin/zsh
if ping -c 1 myhost; then
   echo "test"
fi

which is more concise.

like image 137
Brian Agnew Avatar answered Sep 07 '25 23:09

Brian Agnew