Sammidysam
Sammidysam

Reputation: 43

Batch For Loop: Use wildcard character in string

I have been translating some shell code to MS-DOS Batch. In my code, I have the sample:

for %%i in (%*) do set "clargs=!clargs! %%i"

If I input the argument "-?" (without the quotation marks), it is not added to clargs. I assume it is because '?' is a wildcard character. Is there anything I can do to ensure that for does not do special things because of the question mark being located in the argument?

Upvotes: 1

Views: 4101

Answers (2)

dbenham
dbenham

Reputation: 130919

You are correct, the wild card characters * and ? are always expanded when used within a FOR IN() clause. Unfortunately, there is no way to prevent the wildcard expansion.

You cannot use a FOR loop to access all parameters if they contain wildcards. Instead, you should use a GOTO loop, along with the SHIFT command.

set clargs=%1
:parmLoop
if "%~1" neq "" (
  set clargs=%clargs% %1
  shift /1
  goto :parmLoop
)

Although your sample is quite silly, since the resultant clargs variable ends up containing the same set of values that were already in %*. If you simply want to set a variable containing all values, simply use set clargs=%*

More typically, an "array" of argument variables is created.

set argCnt=0
:parmLoop
if "%~1" equ "" goto :parmsDone
set /a argCnt+=1
set arg%argCnt%=%1
shift /1
goto :parmLoop
:parmsDone

:: Working with the "array" of arguments is best done with delayed expansion
setlocal enableDelayedExpansion
for /l %%N in (1 1 %argCnt%) do echo arg%%N = !arg%%N!

See Windows Bat file optional argument parsing for a robust method to process unix style arguments passed to a Windows batch script.

Upvotes: 2

Magoo
Magoo

Reputation: 80203

@ECHO OFF
SETLOCAL
SET dummy=%*
FOR /f "tokens=1*delims==" %%f IN ('set dummy') DO CALL :addme %%g
ECHO %clargs%
GOTO :eof

:addme
IF "%~1"=="" GOTO :EOF 
IF DEFINED clargs SET clargs=%clargs% %1
IF NOT DEFINED clargs SET clargs=%1
SHIFT
GOTO addme

I severly doubt you'll get a completely bullet-proof solution. The above solution will drop separators (comma, semicolon, equals) for instance. Other solutions may have problems with close-parentheses; there's the perpetual % and ^ problems - but it will handle -?

But for your purposes, from what you've shown, what's wrong with

set clargs=%clargs% %*

(No doubt you'll want to process further, but ve haff vays...)

Upvotes: 0

Related Questions