How to escape % inside double quotes in cmd?

Viewed 24

In cmd I'm trying to do something like

program.exe -command "otherprogram.exe %thing% %path%"

The issue I'm having is that I can't figure out how to escape the % characters when they're inside double quotes, but I need the double quotes because of the spaces in this argument. Basically I don't want cmd to do variable expansion before passing the argument value to program.exe.

Just to be clear, this is directly in cmd, not in a batch script.

2 Answers

A simple semi solution is:

program.exe -command ^"otherprogram.exe %th^ing% %pa^t^h%^"

The positions of the carets inside the variable name are random.

This still could fail, but only for the rare case, if variables exists named thi^ng or pa^t^h

It seems strange, but don't escape the percent signs. Put a caret (the escape sign for every other special char) anywhere within the variable name: echo %^username% or `echo %use^rname%.

The first parsing removes the ^ (because there is (hopefully) no variable with that name). On command line (other than in a batch file), an empty variable doesn't show nothing, but the variable name including the surrounding %'s.

Any further level of parsing then receives the "normal" variable and expands it. Prove:

echo %usern^ame%
call echo %usern^ame%

Not your question, but for the sake of completeness: in a batch script, simply escape the % with another %:

echo %%username%%
call echo %%username%%
Related