Windows CMD Batch: FOR / R with DelayedExpansion

On my desktop there is a folder called "test" . Inside this folder are two files: "file1.txt" and "file2.txt" .

Take a look at this simple script package:

@ECHO OFF

SET test="C:\Users\Tyler\Desktop\test"

ECHO %test%
FOR /R %test% %%F IN (*) DO (
    ECHO %%F
)

As expected, he infers the following:

"C:\Users\Tyler\Desktop\test"
C:\Users\Tyler\Desktop\test\file1.txt
C:\Users\Tyler\Desktop\test\file2.txt

Now consider this option:

@ECHO OFF

SETLOCAL ENABLEDELAYEDEXPANSION

SET test="C:\Users\Tyler\Desktop\test"

ECHO !test!
FOR /R !test! %%F IN (*) DO (
    ECHO %%F
)

ENDLOCAL

I expect his result will not be different. However, here it is:

"C:\Users\Tyler\Desktop\test"

It seems to !test!expand on the line ECHO !test!, but not on the line FOR /R !test!, becoming only !test!. Since this, of course, is not a valid path, the FOR / R loop never iterates.

Why is this? What am I missing?

+4
source share
1

FOR , ECHO, (cmd.exe) FOR, IF REM.

, .

, , FOR.

, , .

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET test="C:\Users\Tyler\Desktop\test"

ECHO !test!
call :doMyLoop test
exit /b

:doMyLoop
set "arg=!%1!"
FOR /R %arg% %%F IN (*) DO (
    ECHO %%F
)
+5

Source: https://habr.com/ru/post/1588867/


All Articles