Using Variables in Windows Batch Files

Posted August 29, 2004 by Rex in Batch file programming

Regardless of the scripting language, the use of variables can greatly enhance the functionality of a script. This tech-recipe demonstrates basic use of variables in MS-DOS or Windows batch files.


The following script demonstrates a trivial example of setting a variable and displaying it:

@echo off
set var=testing 1 2 3
echo The variable is "%var%"

If you put these lines in a file called test.bat and run this batch file by typing test from the command line in the same directory, you will see the following output:

The variable is "testing 1 2 3"

You can view the defined system and user variables by typing set at the command line. You can use any of these variables in your batch files. For instance, the variable %computername% contains the name of the system running the script.

To unset or erase a previously set user variable, use the following command:

set var=

Variables, once set, can be used most anywhere in a batch file where text can go. For example, a variable can be set early in a script to define a directory to be used to copy a series of files for a backup. Later, if the directory needs to be changed, it can be changed once in the batch file rather than in each copy command:

@echo off
set backup=c:\backup\200408
copy file1 %backup%
copy file2 %backup%
.
.
.

The Conversation

Follow the reactions below and share your own thoughts.