0

I have a very weird error occurring in my Batch script where a For loop is only looping once when it should loop many more times (at least 10 times).

Can you tell me why my For loop is only looping once and how I can fix it?

@ECHO off
CLS
SETLOCAL 

SET macroFolder=_PLACE_4DM_FILES_HERE

REM the following for loop only loops once when it should be looping more 
REM because theres over 10 *.4dm files in the folder??
for /r ./%macroFolder% %%i in ("*.4dm") do SET "file=%%i" (
    echo %file%
    REM Note I need to store %%i in a variable so I can edit it later
    REM And placing %%i in a variable within the for loop results in 
    REM the var being empty for some reason. For eg
    SET file=%%i
    ECHO file is %file%
    REM Prints "file is "
)

ECHO.
PAUSE
ENDLOCAL
3
  • try this: for /r "./%macroFolder%" %%i in ("*.4dm") do echo(%%i Commented May 23, 2013 at 4:42
  • Maybe remove the quotes around *.4dm? Commented May 23, 2013 at 4:52
  • You must note that ./%macroFolder% form is exactly the same than just %macroFolder%, that is, %macroFolder% folder in current directory, and usually never used! Commented May 23, 2013 at 5:26

1 Answer 1

5

You have (at least) two problems. The first is that you seem to be mixing the bracketed and non-bracketed form of the for statement:

for /r ./%macroFolder% %%i in ("*.4dm") do SET "file=%%i" (
    blah blah
)

In that case, the non-bracketed bit is executed per-loop-iteration but the bracketed bit executes after loop exit. You can see this with:

for /r ./%macroFolder% %%i in ("*.4dm") do echo 1 (
    echo 2
)

which outputs (in my case where there are three 4dm files):

1 (
1 (
1 (
2

Your second problem is that %% variable expansion is done before the command executed and the for command is a multi-line one, from the for to the closing ) bracket. Any variables you need expanded, that have been set within the loop, need to be done with delayed expansion.

Start with this:

@SETLOCAL enableextensions enabledelayedexpansion
@ECHO off
CLS

SET macroFolder=4dmfiles

for /r ./%macroFolder% %%i in ("*.4dm") do (
    SET file=%%i
    ECHO file is !file!
)

ECHO.
PAUSE
ENDLOCAL

and you'll see (for my three files):

file is C:\Users\Pax\Documents\4dmfiles\1.4dm
file is C:\Users\Pax\Documents\4dmfiles\2.4dm
file is C:\Users\Pax\Documents\4dmfiles\3.4dm
Sign up to request clarification or add additional context in comments.

1 Comment

+1 Good explanation! I had never seen the form for /r ./%macroFolder% %%i in ("*.4dm") do SET "file=%%i" ( blah blah ) before!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.