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?

1

2 Answers 2

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%%
Sign up to request clarification or add additional context in comments.

1 Comment

It worked and I understood why this happens. Thank you for your explanation.
2

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

SETLOCAL ENABLEDELAYEDEXPANSION

Then change %flag2% to !flag2!.

1 Comment

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.

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.