Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch FOR loop with asterisk

I have this single line CMD file TEST.CMD:

for %%f in (%1 %2 %3 %4 %5 %6 %7 %8) DO ECHO %%f

If I run this:

TEST this is a test

it correctly echos each parameter on a separate line, i.e.,

this
is
a
test

However if a parameter contains asterisk it skips it. E.g.,

TEST this is a* test

Results in:

this
is
test

How do I get the parameter with an asterisk to be treated like a normal token?

Thanks.

like image 406
Neil Weicher Avatar asked Jan 31 '26 09:01

Neil Weicher


1 Answers

The simplest method that works for most parameters is to transfer the parameters to an "array" of variables, and then use FOR /L to loop through the array. This is best achieved with delayed expansion.

This technique can process an arbitrary number of parameters - it is not limited to 9.

@echo off
setlocal

:: Transfer parameters to an "array"
set arg.cnt=1
:getArgs
(set arg.%arg.cnt%=%1)
if defined arg.%arg.cnt% (
  set /a arg.cnt+=1
  shift /1
  goto :getArgs
)
set /a arg.cnt-=1

:: Process the "array"
setlocal enableDelayedExpansion
for /l %%N in (1 1 %arg.cnt%) do echo arg %%N = !arg.%%N!
like image 155
dbenham Avatar answered Feb 03 '26 10:02

dbenham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!