0

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?

1

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Certainly. Since there's no setlocal at the start of the routine, any changes made are retained after the procedure ends, so var2 is set to the value entered on the first run when the second run starts. For this reason, it's customary to start with a setlocal which ensures any changes made to the environment are discarded when the procedure ends.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.