Batch File Variables
Contents
Variables
Variables are defined with set and accessed by surrounding a variable's name with percent signs (%).
Best practice is to quote variable substitutions.
set foo=bar IF "%foo%"=="bar" ECHO Equal
Escaping Special Character
Special characters are escaped using the4 caret (^).
set foo=bar ^| baz
As with Unix scripting, when commands spawn subshells that re-interpret tokens, it becomes necessary to add an escaped escape character for each layer.
echo foo ^^^& bar | subroutine
Double-quoted strings are also interpreted literally.
Escaping Double Quotes
Because double-quoted strings are interpreted literally, there is further complication for double-quoted strings containing double quotes.
There is no universal solution as cmd.exe defers interpretation. Consult the specific commands to see if double quotes should be duplicated...
set foo="foo ""bar"" baz"
...or should be escaped in the Unix style...
set foo="foo \"bar\" baz"
Unset Variables
If a variable is not set, no substitution occurs.
set MyVar= echo %MyVar%
This prints %MyVar%.
The same behavior will be seen internally, as in conditional statement.