Tony J
Tony J

Reputation: 3

Nested if statements in Batch not working as expected

When running the following batch file for the first time through CMD I would expect it to print out correctbut instead it prints out error

@echo off
SET /p var1="Enter 1 "
IF "%var1%"=="1" (
 SET /p var2="Enter 1 "
 IF "%var2%"=="1" (
  echo correct
 ) ELSE (
 echo error
 )
)

When running it again in the same CMD session it prints out correct every time afterwards. Am I missing something to make it print out correct the first time?

Upvotes: 0

Views: 1037

Answers (1)

geisterfurz007
geisterfurz007

Reputation: 5874

Have a look at delayed expansion

Whenever you change a value of a variable within a closed block of parenthesis, you have to

1) place setlocal EnableDelayedExpansion at the beginning of your script (common place is beneath the @echo off line) and
2) change %myVar% to !myVar! .

I assume your program behaves like it does, because the cmd window "saves" the value of the variable. You could try to run it with both values 1 and it will return error as you said. In the next run give the program 1 and 2 and it will still say correct.

Delayed is needed because the whole block of the if-statement is calculated at once -> changing a value within without delayed expansion will not be seen as such as it got calculated before.
With delayed expansion however you tell the program, that it has to calculate this part again when it reaches there.

Upvotes: 2

Related Questions