Batch Script Variables

A variable is nothing more than a name given to a particular area in memory that stores a value created by Batch Script. By default, the value of a variable is stored as text, unless specified otherwise. Variable names can contain letters, numbers, underscores and hyphens, but should start with a letter.

When creating a variable, it takes the following format. The equals sign between the variable name and value is known as an assignment operator and will be discussed further in the next section on operators. It is important to omit any spacing between the variable name and equals sign, as well as the equals sign and the value, unless a space is required as part of the value.

set variable_name=value

Below is an example of a variable called 'pname' being set to the value 'Fred Bloggs'.

set pname=Fred Bloggs

When a variable needs to be used, its name must be wrapped in percentage symbols. Below, the variable 'pname' is displayed as part of a message in the console.

:: Name variable.
set pname=Fred Bloggs

:: Display the message 'Hello ' followed by the contents of the pname variable.
echo Hello %pname%

This produces the following output.

Hello Fred Bloggs

Numeric Values in Variables

As mentioned above, all variable values are stored as text by default. If a value in a variable is required within a mathematical calculation, then it must be explicitly defined as a number as follows.

set /A num1 = 6

Here, the variable 'num1' is assigned the value 6. Variables such as this can be used in mathematical operations, such as the one shown below. The variable 'num1' is assigned the value 6 and the variable 'num2' is assigned the value 3. The third variable, 'num3', is assigned the result of multiplying the value of 'num1' with that of 'num2', by using the multiplication operator, '*', which is discussed in the next section on operators. The result is then displayed in a message in the console.

:: Number variables.
set /A num1 = 6
set /A num2 = 3
set /A num3 = num1 * num2

:: Display the message.
echo %num1% multiplied by %num2% equals %num3%

The message displayed contains the values of the first two variables, together with the result of the multiplication contained in the third.

6 multiplied by 3 equals 18