Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run command until it succeeds?

I still use Windows batch-files for basic tasks. One of these is to check my internet connection (pg.bat) which does only do a ping www.google.com

Most of the time, I need to run it a few times until it succeeds (host could not be found error). At first I thought a ping -t would work, but it does not. When the host is not found, it stops right away.

How can I run pg.bat until the ping succeeds? (i.e at least one of the default 4 pings works)

like image 492
Burkhard Avatar asked Aug 22 '15 06:08

Burkhard


People also ask

How do you use till command?

until command in Linux used to execute a set of commands as long as the final command in the 'until' Commands has an exit status which is not zero. It is mostly used where the user needs to execute a set of commands until a condition is true.

How do you know if you've Last command successfully run?

“$?” is a variable that holds the return value of the last executed command. “echo $?” displays 0 if the last command has been successfully executed and displays a non-zero value if some error has occurred.

What will happen when we run the command executed successfully?

On the successful execution, it will return a status zero. From the above result, we can see that after running the script, it has successfully executed the pwd command and displayed the current directory. Also, it has displayed the result of the consequent echo command.

How do I run a command at startup?

On Windows, the simplest way of running a program at startup is to place an executable file in the Startup folder. All the programs that are in this folder will be executed automatically when the computer opens. You can open this folder more easily by pressing WINDOWS KEY + R and then copying this text shell:startup .


1 Answers

In general, you can use the label/goto syntax in a batch file.

:repeat
your-command || goto :repeat
echo Success!

The || will only run the second command if the first one fails. Failure in this case means a nonzero exit code, so it will only work with commands that set %errorlevel% to 0 for success or nonzero for failure.

For the specific case of ping.exe, the exit code is not always nonzero on failure. In that case, you can use find.exe to search the output of ping for a success message and set the errorlevel like we need.

:repeat
(ping -n 1 www.google.com | find "TTL=") || goto :repeat
echo Success!

(Thanks to Stephan for the explanation and solution regarding ping.exe exit codes)

like image 185
Ryan Bemrose Avatar answered Oct 12 '22 22:10

Ryan Bemrose