Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How can I construct a command to ping a host every minute or something, then run a command when it doesn't time out (when the pinged host comes online)?

Basically I want the following pseudocode:

bool ping = pingHost();
while (ping = false) {
    //try again
    ping = pingHost();

Preferably, answers would include instructions for UNIX-like systems (using bash, etc) as well as Windows systems (cmd, PowerShell or Cygwin all work).

share|improve this question
What have you researched and/or tried? Did you try a search for this? – CharlieRB May 17 '13 at 20:07
@CharlieRB ah, I didn't think of that. I just searched for "run command on ping success" or something, which returned much less useful results. – strugee May 18 '13 at 1:02
up vote 4 down vote accepted

First of all please let me point out that you would probably want to use a more complete monitoring software like Nagios for this.

For the basic scripting solution, on Linux I would use Bash for this:

ping -c 1
if [ $? -eq 0 ]; then

Windows is quite similar actually. Put this into a .bat file:

ping -n 1

Explanation: the ping command returns an exit code on both operating systems. On Linux (Bash) you have the $? variable to get this exit code, on Windows it's %errorlevel%. When the ping is successful, the exit code on both operating systems is 0, otherwise it's 1. This value can be used to run your command conditionally.

Adding the loop:

On Linux:

while [ $result -neq 0 ]; do
    ping -c 1

On Windows the same would be:

ping -n 1
    goto loop

Remark: If you want to use it every time the host is online, you can use the crontab on Linux or the Task Scheduler on Windows. If you want to run it every time the host comes online, you need a proper monitoring software.

share|improve this answer
Nice solution. Even easier is to take advantage of conditional execution ping && echo hi will only run the command echo hi if the ping completed successfully. See and – kmort May 17 '13 at 20:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .