Reputation: 139
I have a following batch file:
:LOOP
ping %1
ping %2
goto LOOP
The above file works only with two command line parameters. How to make this work of variable number of command line parameters. For example if four command line parameters were provided at the run time, then it should ping all the four servers.
Any help appreciated
Upvotes: 3
Views: 6304
Reputation: 21
If all that is needed is to ping then just remove the outer loop and use the for statement.
FOR %%x IN (%*) DO ping %%x
If you need to do other things within that outside loop then just use the outer loop and the shift command while checking each iteration for an empty parameter.
@ECHO OFF
:loop_start
IF .%1==. GOTO end
ping %1
SHIFT
GOTO :loop_start
:end
Here is an example of running the latter solution although the output to both is identical. Note I did turn off echo and add a "-n 1" parameter to ping to keep the example output short.
C:\apps\Prod\85000026>tmp.bat 8.8.8.8 localhost 127.0.0.
Pinging 8.8.8.8 with 32 bytes of data:
Reply from 8.8.8.8: bytes=32 time=21ms TTL=52
Ping statistics for 8.8.8.8:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 21ms, Maximum = 21ms, Average = 21ms
Pinging MFGTESTFNTLSYS2 [::1] with 32 bytes of data:
Reply from ::1: time<1ms
Ping statistics for ::1:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0ms
Pinging 127.0.0.1 with 32 bytes of data:
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Ping statistics for 127.0.0.1:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0ms
Upvotes: 0
Reputation: 20044
EDIT: after the comment of Johannes, I added some lines to my original solution to make it work like the original script:
This loops once over all arguments:
:loop
if %1x==x goto :EOF
ping %1
shift
goto :LOOP
This loops endlessly:
:loop2
call :loop %*
goto :loop2
:loop
if %1x==x goto :EOF
ping %1
shift
goto :LOOP
Upvotes: 0
Reputation: 354456
The only option you have to deal with arbitrary numbers of arguments is to use shift
. However, that won't work in the second iteration of your endless loop. You could solve this by first storing all addresses in an array and then iterating over said array, but there is an easier variant.
You can use %*
to get a list of all arguments in a single string and simply loop over the tokens in that string:
@echo off
:loop
for %%x in (%*) do ping %%x
goto :loop
Code can also be found in my SVN repository.
Upvotes: 4