Skip to content

Variables

rbaltrusch edited this page Feb 14, 2021 · 2 revisions

Variables

Declaring variables

The command set may be used to declare, initialize or modify variables. There are only two variable types, string or number, which may be declared as follows:

set my_string=hello
set /a my_number=1

Note the lack of whitespace around the assignment operator (a detailed explanation can be found here).

Accessing variable contents

To access the content of a variable, it needs to be expanded by wrapping it in % signs, as below:

set my_string=hello
echo %my_string%

Sometimes one needs to expand variable contents more than once. This can be achieved using delayed variable expansion. The example below stores a variable name in a variable called my_variable. We then expand my_variable and retrieve the variable named stored in it, and then expand that variable name again to retrieve its contents:

setlocal enabledelayedexpansion
set my_variable=my_string
set my_string=hello

::outputs hello
echo !%my_variable%!

Note that for-loop constructs often mandate the use of delayed expansion, as the state of variables otherwise does not get updated in each subsequent iteration of the loop.

When more than two levels of variable expansion are required, one may use functions or scripts to expand variables to arbitrary depths, as below:

@echo off
goto :main

:expand
setlocal enabledelayedexpansion
endlocal & set rv=!%~1!
exit /b

:main
set my_var1=my_var2
set my_var2=my_var3
set my_var3=hello
call :expand !%my_var1%!
echo %rv%

Calculation

While one will rarely find arithmetic to be required, all common arithmetic operators are available in batch, including:

  • Basic: +, -, *, /, %
  • Assignment: +=, -=, *=, /=, %=
  • Bitwise: &, |, ^

For calculations, use the set /a switch as below:

set /a a=1+1

Variable list

A detailed description of using set to list all variables and their contents in the current scope can be found here.

Clone this wiki locally