Question

Why doesn't this batch script add the value 5 to the variable %counter%? The script always echo the value 2 with which the variable was initialized. Outside a if statement the counter works just fine.

:start

set /a counter=2
set /p message=Message:

set "spam=%message%"
echo %spam%

if "%message%"=="%spam%" (

set /a counter=%counter% + 5

echo %counter%
)

pause

goto 
start
Was it helpful?

Solution

You need to use delayedexpansion. %counter% is being evaluated outside of the If statement but not inside of it.

@echo off
setlocal enabledelayedexpansion

:start

set /a counter=2 
set /p message=Message:

set "spam=%message%" echo %spam%

if "%message%"=="%spam%" ( set /a counter=%counter% + 5

echo !counter! )

pause

goto start
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top