Why doesn't delayed expansion work as paramete

2019-02-19 11:50发布

This question already has an answer here:

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)
)

1条回答
劳资没心,怎么记你
2楼-- · 2019-02-19 12:27

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
查看更多
登录 后发表回答