Search code examples
for-loopbatch-filewildcardglob

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?


Solution

  • 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.