Skip to content

Caret escaping meta characters

johnstevenson edited this page Aug 4, 2016 · 1 revision

When cmd.exe is transforming its command to process, the caret ^ can be used to escape meta characters:

  • Outside a quoted-string, a caret indicates that the next character is literal and has no special meaning, and the caret is removed.
  • Inside a quoted-string a caret has no special meaning and is treated as literal.

For example, the argument my param=%path% can be caret-escaped to prevent variable expansion:

^"my param=^%path^%^"

It is important that the whole argument is escaped, including all double-quotes, so that the parser is never inside a quoted-string.

Limitation

If the argument is the name of the program to execute and it contains whitespace, then it will not be recognized by cmd if it is caret-escaped. This is because the program is identified from the start of the command, delimited by whitespace outside a quoted-string. And because the parser is never inside a quoted-string it will stop when it reaches the first whitespace character.

For example: ^"C:\Program Files\prog^(2^).exe^" will be parsed as "C:\Program. However caret-escaping is not needed in this instance because the ( ) meta characters are already escaped by the outer double-quotes.

This risk can be mitigated by only caret-escaping arguments when absolutely necessary (if they contain internal double-quotes or %...% syntax). Even then it would take a program name like C:\Program Files\pr%og%2.exe for things to break.