Running total in a DOS loop

Posted on 2011-04-29
Last Modified: 2012-06-27
I am having trouble creating a running total in a DOS loop.
this is what I have inside the loop:
     set total=%%H
     set /a tot=%total%+%%H
     echo. %tot%
total is initalized to zero
my results look like:
0+3987 ect.
Any help would be greatly appreciated.  Thanks.
Question by:Steve4400
    LVL 11

    Expert Comment

    LVL 82

    Accepted Solution

    You're a victim of variable expansion in a for loop; the interpreter reads the complete loop, expands all normal variables, and uses these values (enter "help set" for details).
    You need to enable delayed expansion; in addition, there is no need to use percentage signs in a "set /a" command.
    Compare the output of the following commands:
    for /l %a in (1, 1, 10) do (set /a i = %i% + 1)

    Open in new window

    for /l %a in (1, 1, 10) do (set /a j = j + 1)

    Open in new window

    So try something like this (note the "!" being used to expand the "total" variable in the loop!):
    @echo off
    setlocal enabledelayedexpansion
    set total=0
    for /l %%H in (1, 1, 10) do (
         set /a total = total + %%H
         echo !total!

    Open in new window


    Author Closing Comment

    Worked!  Thanks very much.

    Featured Post

    Enabling OSINT in Activity Based Intelligence

    Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

    Join & Write a Comment

    The following is a collection of cases for strange behaviour when using advanced techniques in DOS batch files. You should have some basic experience in batch "programming", as I'm assuming some knowledge and not further explain the basics. For some…
    Being a system administrator some time we require to do things remotely, one of them is installing software. Here I am going to tell you how to install software through wmic (Windows management instrument console). I am not at all saying that this i…
    It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
    This video is in connection to the article "The case of a missing mobile phone (". It will help one to understand clearly the steps to track a lost android phone.

    754 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    19 Experts available now in Live!

    Get 1:1 Help Now