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.

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

  • http://smehrozalam.wordpress.com Syed Mehroz Alam

    Very nice. Helped a lot.

  • Vladimir Orlovsky
    • Jibby

      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.

  • Steve

    Awesome instructions! Thanks a bunch

    • mayini

      nice one,easy to go thru

  • Eric

    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

  • 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

  • Anonymous

    Thank you very much

  • Anonymous

    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.

    • Anonymous

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

      try googleing it

      and why did you say dear sir

    • Sanjay

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

  • Anonymous

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

  • Anonymous
  • Rich

    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!

  • Daniel

    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

    • Bharat Patel

      @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

      • HxCxK

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

  • Jityahoo

    thanks budy………………..

    jitender

  • satheesh

    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 …

    • HxCxK

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

  • JS

    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.

  • http://kirkjoserey.blogspot.com kirkjoserey

    tnks for the information!!!

  • Shiki

    Thanks!

    • Amdo

      how to get ip address if i use ipconfig

  • Lakshmi

    Could sombody pl help me on this

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

    • http://blogs.tech-recipes.com/jimmyselix jimmyselix

      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!

      • Itsmeisuru

        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

  • Helpme

    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

    • http://pulse.yahoo.com/_DZ77M4CVWGOS7B4P6GMACBKBM4 Jalal ud Din

      have you found the answer? I have the same problem

    • Potranquito

      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

  • OrangeBoxTutorials

    Thanks, just needed this for my tutorial! :D

  • Phatsta

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

    • http://www.facebook.com/people/Andrew-Basta/1391154873 Andrew Basta

      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

  • Me

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

  • sonoma

    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?

  • Eduardo Oliveira

    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!

  • hswipf

    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.

  • Sam

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

  • Brian

    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.

  • Ed

    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?

  • Peter

    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?

  • Liz

    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 ?

  • Mike C

    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

  • muldev021

    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

  • Hong

    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?

  • Franck Bayi

    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?

  • jdorsey314

    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.

  • Koni

    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

  • Geoffrey Hunter

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

  • http://www.cladlab.com Geoffrey Hunter

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

  • Darren

    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