Windows 7 / Getting Started

Setting Variables with the Set Command

From the days of MS-DOS version 1, Microsoft's batch file language had two striking deficiencies: the inability to perform string and numerical calculations and the inability to prompt for input.With the command extensions enabled, alternate versions of the set command help remedy these problems to a great extent.

Performing Numerical Calculations in Batch Files

The command set /A expression evaluates a string as a mathematical expression. Any assignment statements in the expression cause CMD to format the result as a string and assign it to a named environment variable. Expression uses standard mathematical syntax.The operators allowed in the expression are listed in order of decreasing precedence:

Operators 		Description
( ) 			Expression grouping.
! ~ - 			Unary operators: boolean NOT, bitwise
                        invert, and arithmetic negative.
* / % 			Multiply, divide, remainder.
+ - 			Add, subtract.
<< >>			Bitwise shift left, shift right.
& 			Bitwise AND.
| ^ 			Bitwise OR and exclusive OR.
= *= /= %= 		Assignment, and the combined
+= -= &= ^= 		operators borrowed from the C programming
|= <<= >>= 		language. A += 3 is the same as
			A = A + 3.
,			Separates multiple expressions.

Any alphanumeric words are taken to indicate environment variables. In an expression, if a named environment variable is undefined or does not contain a number, it is treated as the value 0.Variables are treated as decimal numbers, except that numbers starting with 0x are interpreted as hexadecimal (base 16) and numbers starting with 0 are treated as octal (base 8). Here are some examples:

set A=3
set /A B=A*2, C=2*(B+5)

These statements set environment variables A to 3, B to 6, and C to 22. If you use set /A in a batch file, it is silent, but if you type it on the command line, it displays the last value it calculates. For example, the command

set /A 3+3

types the result 6 without storing the result to any environment variable. It turns the command prompt into a nice, quick calculator.

String calculations-for example, to remove the extension from a filename-are not quite as cleanly implemented.

[Previous] [Contents] [Next]