Using variables in Windows batch files

Contributor Icon Contributed by Rex Date Icon August 29, 2004  
Tag Icon Tagged: Batch file programming

Regardless of the scripting language, the use of variables can greatly enhance the functionality of a script. This recipe demonstrated 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’ll 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%
.
.
.

Previous recipe | Next recipe |
 
  • Dylan
    Nice easy tut for people not familiar with .bat variables. Leared a lot, before i got a bunch of stuff on 'ErrolLevel' stuff. Not what i was looking for.
  • Very nice. Helped a lot.
  • Vladimir Orlovsky
    cmd command line
    set usb=h:

    Created system variable 'usb' with value 'h:'

    How to do the same from the batch file?
    Thanks, Vladimir Orlovsky 4vladimir@gmail.com 2009Feb04Wed14:05
  • Steve
    Awesome instructions! Thanks a bunch
  • thanks alot I can set and echo variables now!

    @echo off
    color 80
    cls

    direct used busses to handlers



    -------------------------------------------
    /make all unused network busses travel here
    retrieve all available information for each
    ip address by storing them in a file called
    network_database

    set ip_address=ipaddress

    echo #%ip_address% > network_database
    network_database{
    #<ip address>
    retrevable information
    retrevable information}






    handlers for all network busses

    ::CALL network_handler
  • Glen Martin
    Thanks, this helped me out! I am a software developer, but don't have much experience with batch files.
  • Mostafa KOTB
    thanks alot. extremely useful
  • pratikshrestha
    Thank you very much
blog comments powered by Disqus