- 1 year ago
CMD variable isn't resolved in for /r loop
When using the for /r
loop in CMD, variable expansion can behave differently compared to other loops. By default, variable expansion is delayed, which means that variables are expanded only once when the loop is first parsed, rather than on each iteration.
To ensure that variables are resolved correctly within the for /r
loop, you can enable delayed variable expansion using the setlocal enabledelayedexpansion
command. Here's an example of how you can use it:
batch@echo off
setlocal enabledelayedexpansion
set "baseDir=C:\SomeDirectory"
for /r "%baseDir%" %%F in (*.txt) do (
set "filePath=%%F"
echo File path: !filePath!
)
In the above example, setlocal enabledelayedexpansion
enables delayed variable expansion. Inside the loop, the !filePath!
syntax is used instead of %filePath%
to expand the variable with delayed expansion.
By using delayed variable expansion, the filePath
variable will be resolved correctly within the loop, even if it changes on each iteration.
Note that if your base directory path contains special characters, you may need to properly quote the path to ensure it is parsed correctly.