2

I want to execute some for loops for every path provided in a variable. The echo !temp! works just fine, however the for commands below it won't work:

@echo off
setlocal enabledelayedexpansion

set paths=(C:\test C:\test2)

for %%p in %paths% do (
    set temp=%%p
    echo !temp!
    for /r !temp! %%f in (*.h) do (echo %%f)
    for /r !temp! %%g in (*.h *.cpp) do (echo %%g)
)
RobbinMarcus
  • 206
  • 2
  • 10
  • 4
    http://stackoverflow.com/questions/4334209/nested-batch-for-loops – CristiFati Feb 25 '16 at 20:08
  • 2
    I think the problem is that the `for` command is handled *before* delayed expansion occurs, according to [this post](http://stackoverflow.com/a/4095133) (see end of phase 2); you can overcome the problem in two ways: 1. change to the `!temp!` directory before the inner `for /R` loops and do not place `!temp!` after `/R`; 2. move the `for /R` loops to a subroutine, pass `!temp!` as an argument and use the `%1` expansion (see `call /?`)... – aschipfl Feb 25 '16 at 20:14
  • @CristiFati this question is indeed the same as your post. I found the solution there. What should I do with this question? Remove? – RobbinMarcus Feb 25 '16 at 20:27
  • Probably someone with enough privileges should mark it as a duplicate. – CristiFati Feb 25 '16 at 20:55

1 Answers1

3

In all for commands syntax patterns:

  FOR %%parameter IN (set) DO command 
  FOR /R [[drive:]path] %%parameter IN (set) DO command 
  FOR /D %%parameter IN (folder_set) DO command 
  FOR /L %%parameter IN (start,step,end) DO command 
  FOR /F ["options"] %%parameter IN (filenameset) DO command 
  FOR /F ["options"] %%parameter IN ("Text string to process") DO command
  FOR /F ["options"] %%parameter IN ('command to process') DO command

all text preceding %%parameter should be known in the first parsing phase. Read How does the Windows Command Interpreter (CMD.EXE) parse scripts?.

However, next script should work as expected

@ECHO OFF
SETLOCAL EnableExtensions EnableDelayedExpansion
set "paths=(C:\test C:\test2)"

for %%p in %paths% do (
    set "temp=%%~p"
    echo !temp!
    call :doit
)

rem skip procedure
goto :domore

:doit
    for /r "%temp%" %%f in (*.h) do (echo %%f)
    for /r "%temp%" %%g in (*.h *.cpp) do (echo %%g)
goto :eof

:domore
Community
  • 1
  • 1
JosefZ
  • 28,460
  • 5
  • 44
  • 83