DOS and Batch Files

SET: Scope and life of variables

If SET is typed at a command prompt the environment variables will be shown. When a variable is created using SET it is in these variables that it is stored. Using the simple batch file

set var=1
set

DOS environment variables

DOS environment variables

Variables created using SET will last as long as the command window is open then be deleted. This means that other batch files, including rerunning the batch file that created them, can access and change these variables until the command window is closed. For this reason it is important that variables be properly initialized unless the variable needs to be accessed again in its current state.

Variables can be deleted by using

SET var=

In summary...

SET - displays all the enviroment variables
SET var - displays var and its value. If var does not exist displays an error message
SET var= - deletes the car variable
SET var=value - sets var equal to value

Care must be taken when defining variables not to include trailing spaces as this batch file demonstrates

@echo off
set var =8
set var=variable
echo. %var%
echo. %var %

Which results in

variable
8

Variables can also be local to a piece of code by using SETLOCAL and ENDLOCAL

@echo off
set var=8
setlocal
set var=20
echo. %var%
endlocal
echo. %var%

Which results in

20
8

This page created 30th December 2011, last modified 31st December, 2011


GoStats stats counter