如何运行命令直到成功? [英] How to run command until it succeeds?

查看:74
本文介绍了如何运行命令直到成功?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍将Windows批处理文件用于基本任务.其中之一是检查我的Internet连接(pg.bat),该连接仅执行ping www.google.com

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

大多数时候,我需要运行几次直到它成功(找不到主机错误).起初,我以为ping -t可以工作,但是不行.如果找不到主机,它将立即停止.

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.

如何在ping成功之前运行pg.bat? (即至少有4种默认ping操作之一)

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

推荐答案

通常,您可以在批处理文件中使用label/goto语法.

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

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

||仅在第一个命令失败时才运行第二个命令.在这种情况下,失败表示退出代码为非零,因此仅适用于将%errorlevel%设置为0表示成功或设置为非零表示失败的命令.

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.

对于ping.exe的特定情况,失败时退出代码并非总是非零.在这种情况下,您可以使用find.exeping的输出中搜索成功消息,并根据需要设置错误级别.

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!

(感谢Stephan提供有关ping.exe退出代码的说明和解决方案)

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

这篇关于如何运行命令直到成功?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆