Using Variables in Windows Batch Files

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.

53 Responses to “Using Variables in Windows Batch Files”

  1. October 16, 2008 at 2:45 am, Dylan said:

    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.

    Reply

  2. December 31, 2008 at 1:33 pm, Syed Mehroz Alam said:

    Very nice. Helped a lot.

    Reply

  3. February 04, 2009 at 10:04 pm, Vladimir Orlovsky said:

    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

    Reply

    • April 30, 2013 at 6:03 am, Jibby said:

      You have to use the set /p command. Here’s how it works: “set /p usb=”. It waits until an input has been given, and ENTER has been pressed, and then it sets the variable and moves on to the next command.

      Reply

  4. February 18, 2009 at 7:36 am, Steve said:

    Awesome instructions! Thanks a bunch

    Reply

    • July 01, 2010 at 12:43 pm, mayini said:

      nice one,easy to go thru

      Reply

  5. April 27, 2009 at 9:01 am, Eric said:

    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

    Reply

  6. July 13, 2009 at 7:08 pm, Glen Martin said:

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

    Reply

  7. August 18, 2009 at 8:57 am, Mostafa KOTB said:

    thanks alot. extremely useful

    Reply

  8. September 14, 2009 at 6:39 am, Anonymous said:

    Thank you very much

    Reply

  9. January 01, 2010 at 11:00 am, Anonymous said:

    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.

    Reply

    • January 27, 2010 at 12:56 am, Anonymous said:

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

      try googleing it

      and why did you say dear sir

      Reply

    • July 27, 2010 at 3:56 pm, Sanjay said:

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

      Reply

  10. January 27, 2010 at 12:53 am, Anonymous said:

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

    Reply

  11. February 10, 2010 at 4:54 pm, Anonymous said:

    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

    Reply

  12. February 23, 2010 at 5:39 pm, Rich said:

    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!

    Reply

  13. July 15, 2010 at 5:42 am, Daniel said:

    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

    Reply

    • July 23, 2010 at 7:08 am, Bharat Patel said:

      @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

      Reply

      • August 19, 2010 at 7:40 pm, HxCxK said:

        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..

        Reply

  14. July 31, 2010 at 11:44 am, Jityahoo said:

    thanks budy………………..

    jitender

    Reply

  15. August 06, 2010 at 9:41 am, satheesh said:

    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 …

    Reply

    • August 19, 2010 at 7:38 pm, HxCxK said:

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

      Reply

  16. August 10, 2010 at 10:43 am, JS said:

    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.

    Reply

  17. August 28, 2010 at 5:07 am, kirkjoserey said:

    tnks for the information!!!

    Reply

  18. August 29, 2010 at 10:57 am, Shiki said:

    Thanks!

    Reply

    • August 31, 2010 at 6:11 am, Amdo said:

      how to get ip address if i use ipconfig

      Reply

  19. August 31, 2010 at 7:09 am, Lakshmi said:

    Could sombody pl help me on this

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

    Reply

    • September 08, 2010 at 4:53 am, jimmyselix said:

      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!

      Reply

      • September 10, 2010 at 1:09 pm, Itsmeisuru said:

        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

        Reply

  20. September 18, 2010 at 9:02 am, Helpme said:

    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

    Reply

    • December 06, 2010 at 12:14 pm, Jalal ud Din said:

      have you found the answer? I have the same problem

      Reply

    • February 11, 2011 at 6:16 am, Potranquito said:

      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

      Reply

  21. October 10, 2010 at 8:28 pm, OrangeBoxTutorials said:

    Thanks, just needed this for my tutorial! :D

    Reply

  22. October 20, 2010 at 8:17 am, Phatsta said:

    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 :)

    Reply

    • April 26, 2011 at 1:51 pm, Andrew Basta said:

      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

      Reply

  23. October 20, 2010 at 2:27 pm, Me said:

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

    Reply

  24. March 02, 2011 at 11:55 pm, sonoma said:

    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?

    Reply

  25. October 29, 2011 at 7:55 am, Eduardo Oliveira said:

    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!

    Reply

  26. January 20, 2012 at 5:18 pm, hswipf said:

    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.

    Reply

  27. April 11, 2012 at 10:52 pm, Sam said:

    %%a is used in place of a temporary variable (i.e. in a for loop) INSIDE a batch file.

    %a is used as a temporary variable when OUTSIDE a batch file (i.e. running a command straight from cmd.exe).

    Same thing, but written differently in different locations. I’m guessing in your situation you should be using %a.

    Reply

  28. May 03, 2012 at 5:56 pm, Brian said:

    I want to take the outputs of this series of questions

    @echo off
    Set /p ip=What is the IP of the computer you are replacing?
    Set /p subnet=What is the Subnet mask of the computer you are replacing?
    Set /p Gateway=What is the gateway of the computer your are replacing?
    Set /p DNS=What is the DNS entry of the computer you are replacing?
    Set /p Squadron=What is your squadron name?
    Set /p server=What is your OOMA server name?
    Set /p Computername=what is the computer name of the computer you are replacing?

    and insert them into either text files or other cmd files to complete the task or reconfiguring a replacement computer. The task has to be repeated several times by people that are not always the most computer savy.

    Reply

  29. October 11, 2012 at 3:43 pm, Ed said:

    How do I test for a variable passed into a batch file?

    I have a batch file that is called with up to 8 variables. How do I test for existence of %2 – %8 and respond based on the answer?

    I’ve tried
    if %6==”" goto end
    if %6==null goto end
    if not exist %6 goto end

    None of these work. Any ideas?

    Reply

  30. October 12, 2012 at 9:26 am, Peter said:

    yeah, i want to be able to use variables. How do I set a variable based on a user’s input. So the variable will be whatever the user enters?

    Reply

  31. October 24, 2012 at 7:05 pm, Liz said:

    Yes, I would love some explanations of %%a, etc. No one EVER explains any of this. I have been researching for hours and I’m extremely frustrated.

    How would I capture the value of find /c “ATR” 0 ?

    Reply

  32. November 12, 2012 at 12:52 pm, Mike C said:

    Doing the following: –
    set Prevdate = %date:~6,4%%date:~3,2%%date~0,2%
    ..then using variable within a file copy
    xcopy \\input_unc\g\dir\filename_%Prevdate%_rest.txt Somewhere\somewhere_else

    However using %Prevdate% within the filename string is not recognized

    Reply

  33. December 20, 2012 at 2:05 am, muldev021 said:

    Need a batch file the will check my xml file and replace value of a string. hope you can help

    @echo off
    setlocal EnableDelayedExpansion
    set “_search=value1″
    set “_replace=A”
    set “_search=value2″
    set “_replace=B”

    for /F “delims=” %%a in (LastestFRN.xml) DO (
    set line=%%a
    setlocal EnableDelayedExpansion
    >> LastestFRN3.xml echo(!line:%_search%=%_replace%!
    endlocal
    )
    del LastestFRN.xml
    rename LastestFRN3.xml LastestFRN.xml

    Reply

  34. February 22, 2013 at 9:55 pm, Hong said:

    I need to make a copy of a text file from one folder (folder A) to another. Folder A changes every month depending on the year and month example 2013_02 (next month this folder will change to 2013_03. How do I write a bat code to recognize the change of the folder name?

    Reply

  35. April 04, 2013 at 6:10 am, Franck Bayi said:

    Hi. My Name is Franck, i’m a Cameroonian university student learning computer engineering. We’v been given an assignment which is to make a batch file (program) which acts like a phone’s annual. The problem is i don’t know much about batch s and the documents i have on them are not very explicit. Please can you help me?

    Reply

  36. April 21, 2013 at 7:35 am, jdorsey314 said:

    thats cool, I didn’t know you could use spaces like “testing 1 2 3″. but what I really wanted to know was: is there a limit to how many different “set = ” a batch file can use? 100? 400? I am planning on making a batch file that uses 400, and I wanted to know for sure before I go and try.

    Reply

  37. August 14, 2013 at 3:24 am, Koni said:

    Hi,

    I tried like you do but I have a problem. Here is how i try to display :

    @echo off
    for %%G in (1 2 3) do (
    set T_FILENAME=test%%G.txt
    echo %T_FILENAME%
    pause
    )

    And i get nothing displayed except “press a key to continue…” (thanks to “pause”). An idea?

    Thanks for help

    Reply

  38. October 22, 2013 at 11:59 pm, Geoffrey Hunter said:

    Helpful information! Just learning more about Windows scripting after being familiar with Linux style bash scripting.

    Reply

  39. October 23, 2013 at 10:32 pm, Geoffrey Hunter said:

    Thanks for the tips! You should mention something about variable scope, i.e. can you access variables from sub-routines?

    Reply

  40. January 15, 2014 at 10:17 am, Darren said:

    Great tutorial. I have another related question and can’t seem to google this.
    I am running a number of FTP’s from batch (87 to be exact) .. I run these every day.
    I am tired of having to input the username and password, and for security reasons, remove it every time.
    Is there a way I can store a username and password someplace then just have all the FTP batch files just call them.
    Here is what I am using right now:

    @echo off
    set ftptxt=”D:\location on my PC\file.txt”
    set upfile=”D:\location on my pc\logtime%cYEAR%%cMONTH%%cDAY%.txt”
    set dataset=PRJU.ARBEAD2.TEST
    >> %ftptxt% echo darren
    >> %ftptxt% echo PaSsWorD
    >> %ftptxt% echo prompt
    >> %ftptxt% echo quote site lrecl=500 recfm=fb cyl pri=1 sec=1
    >> %ftptxt% echo PUT %upfile% ‘%dataset%’
    >> %ftptxt% echo close
    >> %ftptxt% echo pause
    :: -s:filename = is used to access the file containing the ftp commands
    ftp -v -i -s:%ftptxt% http://ftp.prod.bank.ca

    Reply

Leave a Reply