Mark Said Camilleri
Mark Said Camilleri

Reputation: 388

Batch IF statement always returning false?

OK, so I have this:

:ask
SET /p answer = Hello user. Do you want to use this program? (y/n) 

IF [/i] %answer% == y GOTO yes
IF [/i] %answer% == n (GOTO no) ELSE (ECHO Your input was not accepted. Please try again. & GOTO ask)

:yes
...
...

:no
pause

The problem is that both if statements are returning false and it is constantly asking for my input. I wanted it so that if the answer is neither y or n the user must re-input their answer.

Any help?

Thanks

Upvotes: 2

Views: 644

Answers (2)

npocmaka
npocmaka

Reputation: 57252

remove the space after answer :

SET /p answer= Hello user. Do you want to use this program? (y/n)

in your original code you are creating a variable named %answer % instead of %answer%

EDIT Remove also the rectangular brackets in IF conditions...

:ask
@echo off
SET /p answer= Hello user. Do you want to use this program? (y/n) 

IF /i "%answer%" == "y" GOTO :yes
IF /i "%answer%" == "n" (
 GOTO :no
) ELSE ( 
 ECHO Your input was not accepted. Please try again.
 GOTO :ask
)

:yes
rem

:no
rem
pause

Upvotes: 1

MC ND
MC ND

Reputation: 70923

Remove spaces on left side of equal sign to avoid declaring a variable with a space in its name. Add quotes to avoid problems with some characters (&<>|)

SET /p "answer=Hello user. Do you want to use this program? (y/n)"

The ignore case in the IF command does not include []. Also, add quotes to avoid problems with empty answers.

IF /i "%answer%"=="y" GOTO yes

Upvotes: 2

Related Questions