.bat 语句 例
ping /n 1 /w 500 kms.ustc.edu.cn >nul && (goto ok) || (goto error)
就是ping成功了转到OK标签去执行,不成功了转到error去执行。
原理其实就是根据 ping 操作的返回值来进行跳转。你可以试试 ping 一个不成功的地址,结果是1,正常的地址成功了,结果是0,从而根据这个errorlevel结果来做跳转。
题目中的写法是简化写法。你用 if 来做判断也可以。
C:\Documents and Settings\test>ping /n 1 /w 500 xxx.xxx.xx
Packets: Sent = 1, Received = 0, Lost = 1 (100% loss),
C:\Documents and Settings\test>echo %errorlevel%
1
C:\Documents and Settings\test>ping /n 1 /w 500 www.baidu.com
Pinging www.a.shifen.com [115.239.210.26] with 32 bytes of data:
Reply from 115.239.210.26: bytes=32 time=17ms TTL=54
Ping statistics for 115.239.210.26:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 17ms, Maximum = 17ms, Average = 17ms
C:\Documents and Settings\test>echo %errorlevel%
0
>nul 是把输出屏蔽的意思。这样脚本运行的过程就不会有输出影响美观了。