TheCrafter
TheCrafter

Reputation: 1939

Cannot take user input in batch file while in if statement

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?

Upvotes: 1

Views: 1766

Answers (2)

Magoo
Magoo

Reputation: 80213

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%%

Upvotes: 4

aphoria
aphoria

Reputation: 20209

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

SETLOCAL ENABLEDELAYEDEXPANSION

Then change %flag2% to !flag2!.

Upvotes: 2

Related Questions