Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to prevent variable resolving (or to escape percent sign) in for loop in windows batch file? [duplicate]

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.

like image 659
rsk82 Avatar asked Nov 28 '13 21:11

rsk82


People also ask

What Is percent sign in batch file?

The percent sign (%) is a special case. On the command line, it does not need quoting or escaping unless two of them are used to indicate a variable, such as %OS%. But in a batch file, you have to use a double percent sign (%%) to yield a single percent sign (%).

How do you exit the percent sign in CMD?

In batch files, the percent sign may be "escaped" by using a double percent sign ( %% ). That way, a single percent sign will be used as literal within the command line, instead of being further interpreted.

How do you repeat a batch file?

Pressing "y" would use the goto command and go back to start and rerun the batch file. Pressing any other key would exit the batch file.


1 Answers

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%"
like image 169
Endoro Avatar answered Sep 22 '22 05:09

Endoro