Using variables in Windows batch files

Contributor Icon Contributed by Rex  
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%
.
.
.

 

38 Comments -


  1. Dylan said on October 16, 2008

    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.

  2. Syed Mehroz Alam said on December 31, 2008

    Very nice. Helped a lot.

  3. Vladimir Orlovsky said on February 4, 2009

    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

  4. Steve said on February 18, 2009

    Awesome instructions! Thanks a bunch

  5. Eric said on April 27, 2009

    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{
    #
    retrevable information
    retrevable information}

    handlers for all network busses

    ::CALL network_handler

  6. Glen Martin said on July 13, 2009

    Thanks, this helped me out! I am a software developer, but don’t have much experience with batch files.

  7. Mostafa KOTB said on August 18, 2009

    thanks alot. extremely useful

  8. Anonymous said on September 14, 2009

    Thank you very much

  9. Anonymous said on January 1, 2010

    Dear Sir,

    Sir, I have tried to make a bootable CD . It is giving some kind of errors. Please, It is Heartily request to you. So Help me and give me some step by step Instructions to make a BOOTABLE CD. It will be very helpful for me……

    Warm heartily Regards
    Basavaraj.

  10. Anonymous said on January 27, 2010

    you need to show many other types of variables like:
    %sec%, %time%, %input%

  11. Anonymous said on January 27, 2010

    well if your trying to do that then you wont get far here

    try googleing it

    and why did you say dear sir

  12. Anonymous said on February 10, 2010

    this stuff is old news to me now if anyone knows how to increase or decreese a varrible then please tell me

    but if you want a rpglike battle system in batch email me at
    rater193@gmail.com
    it works just as well as increesing or decreesing varribles

  13. Rich said on February 23, 2010

    I want to create a batch file that looks at a list of files, and zips like files together, then deletes the files that were zipped.

    Example: a folder contains:

    file1.xyz
    file1_6.abc
    file2_1.abc
    file3.xyz
    file3_0.abc

    The batch file should:
    1) combine file1.xyz and file1_6.abc into a file called file1_6.zip
    2) skip file2_1.abc (since it has no other file “like” it)
    3) combine file3.xyz and file3_0.abc into a file called file3_0.zip
    4) delete file1.xyz, file1_6.abc, file3.xyz, file3_0.abc (since they are now in a new zip file)

    This is just a simple example – the actual file list may consist of 100’s of files…

    Right now I create a list of the files with the dir command, import into excel, go through a whole lot of mmanipulation to create a batch file that contains a line of code for every specific file combination. I’d like to use variables and looping? to recurse the directory to perform the needed actions.

    HELP!

  14. mayini said on July 1, 2010

    nice one,easy to go thru

  15. Daniel said on July 15, 2010

    Hey,

    i was wondering a long time ago if it was possible to use the value of one variable, in order to define another.

    example:

    set /p var1=Please enter a number:
    set /a value=string%var1%
    echo %value%

    any help would be greatly appreciated

  16. Bharat Patel said on July 23, 2010

    @ECHO OFF
    rem set N=%1%
    set N=100
    FOR /L %%X IN (12,1,%N%)do (
    echo “X i %%X”
    set FL=153_%%X.rar
    echo %FL%
    rem copy 153_1.rar %FL%
    copy 153_1.rar 153_%%X.rar
    )

    above script creates 88 files. It copy 153_1.rar file to 153_12.rar, 153_13.rar ….153_100.rar

  17. Sanjay said on July 27, 2010

    Is it making the grinding noise? If so the PC is suspect and you need to call Microsoft. It happen to me. :-(

  18. Jityahoo said on July 31, 2010

    thanks budy………………..

    jitender

  19. satheesh said on August 6, 2010

    I need to connect to database and need to get the values from table and store in a variable in bat file can any one help me on this asap …

  20. JS said on August 10, 2010

    I have files with same name in multiple folders say 123.txt in folder1,foder2…folder9 in C drive. I want to copy all this files to d:test folder by appending them with alphabet or as a.txt, b.txt …h.txt etc.. in sequence. Any help is appreciated.

  21. HxCxK said on August 19, 2010

    That sounds like a sticky situation, im sure that it would be possible but not from the “web side of things”

  22. HxCxK said on August 19, 2010

    is there a way to take say
    1.txt, 2.exe, 3.jpg
    and put them in to “4.rar”
    i just want to rar my files before i send them off in the email my bat file sends..

  23. kirkjoserey said on August 28, 2010

    tnks for the information!!!

  24. Shiki said on August 29, 2010

    Thanks!

  25. Amdo said on August 31, 2010

    how to get ip address if i use ipconfig

  26. Lakshmi said on August 31, 2010

    Could sombody pl help me on this

    How can i set output of some command to a variable in batch file?

  27. jimmyselix said on September 8, 2010

    ahh! you can do this via a variable in the batch file. you’d need to files or use functions to do this.

    so we have two files; input.bat and variable.bat

    we will have a command in input.bat that creates a basic directory listing of a folder and then can pass the variable onto the variable.bat which will then echo the results to a log.txt file.

    variable.bat:
    echo %1 >> log.txt

    input.bat
    for /f “tokens=1 delims=” %%a in (‘dir /b “C:”‘) do (variable.bat %%a)

    it should do a dir with bare flag, C: and then send just the folder names to the variable.bat. the %1 is the variable thats read from the input.bat. you can use %1 %2 %3 and have 3 variables passed :)

    hope that helps!

  28. Itsmeisuru said on September 10, 2010

    I want to make a folder with the name of input argument in to the .bat file from .c file.

    ::assume the input argument is ‘5′

    @echo off
    ECHO DirName %1% ::confirm the input (Display DirName 5)

    set f = %1% ::assigning the argument

    MD f :: here what I want is to make a folder name, 5 (line 7)

    copy 1.jpg f1.jpg :: I want to copy the jpg to newly made folder. (line 9)

    But these line 7 and 9 gives Syntax errors

    please help me someone

    ::ECHO C:TEMP FOLDER ALREADY EXISTS
    copy 1.jpg 11.jpg

    pause

  29. Helpme said on September 18, 2010

    Hello,
    In bat scripting how can i get the value of a variable within a variable.
    Ex:
    SET Colour1=RED
    SET Colour2=BLUE
    SET Colour3=GREEN
    SET count=1
    SET Colour=Colour%count%
    ECHO Colour is %Colour%

    Now Color shows Color1, as output…
    How can i get Colour to show value of Color1 ie RED

  30. OrangeBoxTutorials said on October 10, 2010

    Thanks, just needed this for my tutorial! :D

  31. Phatsta said on October 20, 2010

    When you’ve learned this it’s easy to use it for backup purposes, like this one:

    —————————————————————————–
    md “C:testBackup %date%”
    set bkpdir=”C:testBackup %date%”

    xcopy C:temp %bkpdir% /E /C /Q /H /Y
    —————————————————————————–

    All you have to do is schedule this script to run each night or whenever you like, using windows scheduler. Works like a charm :)

  32. Me said on October 20, 2010

    How about answering the question ‘using variables in batch files’ …
    printing the variables doesn’t really amount to ‘use’

  33. Jalal ud Din said on December 6, 2010

    have you found the answer? I have the same problem

  34. Potranquito said on February 11, 2011

    The next code does the job. I know it does the job using a different approach, but I guess the end result is the same as you wanted it.
    Hope it helps…
    Note: Because of the line “set /a count=%count%+1″ this script works well under cmd, but not under good old command.com.

    SET count=0

    :new_col
    set /a count=%count%+1
    if %count%==9 goto end
    SET Colour=Colour%count%
    goto get_col

    :get_col
    if “%Colour%”==”Colour1″ set Colour=BLACK
    if “%Colour%”==”Colour2″ set Colour=BLUE
    if “%Colour%”==”Colour3″ set Colour=GREEN
    if “%Colour%”==”Colour4″ set Colour=CYAN
    if “%Colour%”==”Colour5″ set Colour=RED
    if “%Colour%”==”Colour6″ set Colour=PURPLE
    if “%Colour%”==”Colour7″ set Colour=ORANGE
    if “%Colour%”==”Colour8″ set Colour=GRAY
    goto show_col

    :show_col
    ECHO Colour is %Colour%
    goto new_col

    :end

  35. sonoma said on March 2, 2011

    I like the nested () after the do in the for loop. But seem to be having problems with nested for loops within it, as I want to take the first loop variable and add the second loop variable to it using the SET /A command…doesn’t seem to work. would be a great way to increment or decrement a number for file manipulation….
    any ideas?

  36. Andrew Basta said on April 26, 2011

    I don’t like Windows-style data output and using %date:~6,4%-%date:~3,2%-%date:~0,2% for backup, it gives YYYY-MM-DD format

  37. Eduardo Oliveira said on October 29, 2011

    I was needing a help to unset a variable, and i find it here!
    And reading the comments learn how to read args in bat/cmd and how to make a loop in a really easy way!

    Thanks for your post and commenters!

  38. hswipf said on January 20, 2012

    I’ve seen %%a or %%x used here or other sites that explain how to use variables in batch files – BUT NO ONE EXPLAINS THE %%A. When you copy and paste a command that should read all the lines from a file and echo or process each line I get a:

    %%A was unexpected at this time.

 

RSS feed for comments on this post. TrackBack URL

Leave a comment -