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)
)
4
  • 4
    stackoverflow.com/questions/4334209/nested-batch-for-loops Commented Feb 25, 2016 at 20:08
  • 2
    I think the problem is that the for command is handled before delayed expansion occurs, according to this post (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 /?)... Commented Feb 25, 2016 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? Commented Feb 25, 2016 at 20:27
  • Probably someone with enough privileges should mark it as a duplicate. Commented Feb 25, 2016 at 20:55

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.