1

I want to get input from user in a batch file but while it works fine when I am outside of if statement, when I get inside it doesn't get user's input.

@echo off

set /p flag=Enter letter 'y': 

echo %flag%

if %flag% == y (
    set /p flag2=Enter random string:

    echo flag2: %flag2%
)

pause

In the above example after I enter 'y' for the first prompt, it prints the contents of %flag% but then in the second prompt inside if statement, the %flag2% gets no value.

Output:

Enter letter 'y': y
y
Enter random string:lalala
flag2:
Press any key to continue . . .

Why is this happening?

TheCrafter
  • 1,909
  • 2
  • 23
  • 44
  • possible duplicate of [Problem with user input in my batch file](http://stackoverflow.com/questions/916413/problem-with-user-input-in-my-batch-file) – indiv Feb 03 '15 at 20:41

2 Answers2

4

Within a block statement (a parenthesised series of statements), the entire block is parsed and then executed. Any %var% within the block will be replaced by that variable's value at the time the block is parsed - before the block is executed - the same thing applies to a FOR ... DO (block).

Hence, IF (something) else (somethingelse) will be executed using the values of %variables% at the time the IF is encountered.

Two common ways to overcome this are 1) to use setlocal enabledelayedexpansion and use !var! in place of %var% to access the changed value of var or 2) to call a subroutine to perform further processing using the changed values.

Note therefore the use of CALL ECHO %%var%% which displays the changed value of var. CALL ECHO %%errorlevel%% displays, but sadly then RESETS errorlevel.

try

CALL echo flag2: %%flag2%%
Magoo
  • 77,302
  • 8
  • 62
  • 84
2

You need to add this line at the top or above the IF statement:

SETLOCAL ENABLEDELAYEDEXPANSION

Then change %flag2% to !flag2!.

aphoria
  • 19,796
  • 7
  • 64
  • 73
  • Thanks for your answer. It worked but I will accept Magoo's answer as it is more complete, thus, more useful to other people encountering this problem. – TheCrafter Feb 03 '15 at 20:52