User Variables

Table of contents:

Variables are set using the SETcommand. Variable names are letters and numbers.

Variable Scope

User variables are saved into the command shell environment space in which the script is running. This implies that if you modify a variable, it will stay modified after the script has concluded if the shell remains. Of course, you are not modifying the underlying environment, only that of the current shell so this rarely causes a problem, but beware.

You can use the setlocalcommand force Windows to create a local memory space for the environment of a script.

@echo off

TESTVAR is abcd

Note: If setlocal is called within a script, an implied endlocal is executed at the end of a script. Setlocal commands can be nested to provide tight control over your memory space.


The SET command supports math (arithmetic) on the right-side of the equal sign. SET /A TESTVAR= 2*2/4 will assign the value 1 to TESTVAR. The shell does not require the use of % around variable when being used in math. So
Set /a TT = 4
set /a TT2 = TT*4
Echo %TT2%
will substitute TT with %TT% and return set TT2 to 8.

A rather extensive set of operations are supported as are hexadecimal (0x12) and octal (022) values, HOWEVER, only integer operations are supported.

User Input

The SET command can be used to prompt for user input.
SET /P info=Pick a number from 1 to 10:
will use the text after the = as a prompt for the user and assign the value to No value assigned. Note: You'll want to add space after the prompt string to keep things clear.

Variable Expansion

There is a complex issue with variable expansion. Essentially cmd will expand all instances of a variable in a single statement when it is first evaluated. This generally rears its ugly head when you are using the for command or a loop and can be overcome by using Setlocal EnableDelayedExpansion We will discuss this in detail when we discuss for. For more read set /?
Created by system. Last Modification: Monday 28 of November, 2016 16:54:02 EST by gmartin.