how to prevent variable resolving (or to escape percent sign) in for loop in windows batch file?
batch-file, for-loop, variables
Solution
Short course in escaping.
@ECHO OFF &SETLOCAL
FOR /F "delims=" %%F IN ('echo X:\myapp\%AppData%') DO (
echo %%F
)
FOR /F "delims=" %%F IN ('echo X:\myapp\^^%%AppData^^%%') DO (
echo %%F
)
FOR /F "delims=" %%F IN ('echo "X:\myapp\^^%%AppData^^%%"') DO (
echo %%F
)
FOR /F "delims=" %%F IN ('echo ^^"X:\myapp\^%%AppData^%%^"') DO (
echo %%F
)
Output:
X:\myapp\C:\Users\User\AppData\Roaming
X:\myapp\%AppData%
"X:\myapp\^^%AppData^^%"
"X:\myapp\%AppData%"
Problem
For example I have such loop that calls dir on a folder whose name contains percent signs so interpreter tries to resolve characters between these as a variable. Such folders are for example common in virtualizing solutions (for example ThinApp), that is data which would be stored in local user AppData is instead written to for example: X:\My Virtualized App\%AppData%. And of course I know that it is possible to dir through it by doubling the %'s but it is not possible to convince interpreter to not resolve such variable in a for loop, for example: ``` FOR /F "tokens=*" %%F IN ('dir /b /s X:\myapp\%AppData% ') DO @( echo %%F ) ``` Here no matter what I tried , doubling, quadrupling percents, or adding carets made no difference. The path passed to dir command has resolved appdata and thus is invalid having two drive specifications.