Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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();
}
runCommand("whatever");

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

1 Answer 1

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:

#!/bin/bash
ping -c 1 yourhost.com
if [ $? -eq 0 ]; then
    your_command
fi

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

ping -n 1 yourhost.com
IF %ERRORLEVEL%==0 (
    your_command
)

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:

#!/bin/bash
result=1
while [ $result -neq 0 ]; do
    ping -c 1 yourhost.com
    result=$?
done

On Windows the same would be:

:loop
ping -n 1 yourhost.com
IF NOT %ERRORLEVEL%==0 (
    goto loop
)
your_command

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
2  
Nice solution. Even easier is to take advantage of conditional execution ping yourhost.com && echo hi will only run the command echo hi if the ping completed successfully. See dostips.com/?t=Snippets.ConditionalExecution and ss64.com/bash/syntax-execute.html –  kmort May 17 '13 at 20:31

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.