Batch Counter in For-Do loop

  • Thread starter Thread starter homerlex
  • Start date Start date
H

homerlex

I have a batch file that executes a bunch of apps and counts the
errors. The issue is that I can't see the current error count from
within the for loop.

I've stripped down the batch file to the following. When I run it the
ERROR_COUNT is shown properly at the end but always shows as zero in
the for loop. What am I doing wrong?

I have similar issue testing %errorlevel% from within the loop (though
this is not shown in the sample below)

@Echo Off

SET EXECUTION_LIST=1.exe 2.exe 3.exe 4.exe
SET ERROR_COUNT=0


FOR %%d in (%EXECUTION_LIST%) do (
echo ****************************************
echo Running: %%d
echo ----------------------------------------
rem %%d
SET /A ERROR_COUNT+=1
echo %ERROR_COUNT%
echo ----------------------------------------
echo ****************************************
)

echo Errors: %ERROR_COUNT%
 
homerlex said:
I have a batch file that executes a bunch of apps and counts the
errors. The issue is that I can't see the current error count from
within the for loop.

I've stripped down the batch file to the following. When I run it the
ERROR_COUNT is shown properly at the end but always shows as zero in
the for loop. What am I doing wrong?

The bracketted set of commands immediately following the "do" command are
processed as one command. The main effect is that all %variable% references
are resolved ONCE ONLY just before the first command in the list is
executed. Even though the variable's value changes through the execution in
the loop, the "echo %error_count%" still shows its initial value for the
reason I have just recounted.

There are two solutions, the first one being to enable delayed variable
expansion by putting this command at the front of your batch script:

setlocal enabledelayedexpansion

and then change the echo command to:

echo !error_count!

Note that the setlocal command will have side effects that might cause
unexpected problems depending on what else your script does, the main one
being that any changes made by the script to variables (i.e. to pass
information back to the calling script) will be rolled back.

The second solution is to move the problematic reference to an internal
subroutine as illustrated below:
I have similar issue testing %errorlevel% from within the loop (though
this is not shown in the sample below)

IMHO, this is the same problem...
@Echo Off

SET EXECUTION_LIST=1.exe 2.exe 3.exe 4.exe
SET ERROR_COUNT=0


FOR %%d in (%EXECUTION_LIST%) do (
echo ****************************************
echo Running: %%d
echo ----------------------------------------
rem %%d
SET /A ERROR_COUNT+=1

replace the following line:
echo %ERROR_COUNT%

with this:

call:show_error
echo ----------------------------------------
echo ****************************************
)

echo Errors: %ERROR_COUNT%

and add the show_error routine:

goto:eof
:show_error
echo %error_count%
goto:eof


/Al
 
Back
Top