批处理IF语句总是返回false?

时间:2014-03-06 18:11:09

标签: windows batch-file if-statement windows-7 cmd

好的,我有这个:

: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

问题是if语句都返回false并且不断询问我的输入。我想要它,如果答案既不是y或n,用户必须重新输入他们的答案。

任何帮助?

由于

2 个答案:

答案 0 :(得分:2)

删除等号左侧的空格,以避免声明名称中带有空格的变量。添加引号以避免某些字符出现问题(&<> |)

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

IF命令中的忽略大小写不包括[]。另外,添加引号以避免空答案出现问题。

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

答案 1 :(得分:1)

删除answer之后的空格:

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

在原始代码中,您创建了一个名为%answer %的变量,而不是%answer%

编辑删除IF条件中的矩形括号...

: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