To create a simple variable and assign it to a value or string use the SET
command:
SET var=10
Here, the code declares a new variable var
with a value of 10
. By default all variables are stored internally as strings; this means that the value 10
is no different to foo1234
or Hello, World!
Quotation marks used will be included in the variable's value:
SET var="new value" <-- %var% == '"new value"'
Batch language considers spaces to be acceptable parts of variable names. For instance, set var = 10
will result in a variable called var
that contains the value 10
(note the extra space to the right of var and the left of the 10).
In order to prevent spaces, use quotation marks around the entire assignment; the variable name and value. This also prevents accidental trailing spaces at the end of the line (the ␣
character denotes a space):
SET␣var=my␣new␣value␣ <-- '%var%' == 'my new value '
SET␣"var=my␣new␣value"␣ <-- '%var%' == 'my new value'
Also, use quotation marks when joining multiple statements with &
or |
- alternatively, put the symbol directly after the end of the variable's value:
SET var=val & goto :next <-- '%var%' == 'val '
SET "var=val" & goto :next <-- '%var%' == 'val'
SET var=val& goto :next <-- '%var%' == 'val'