尝试在批处理编程中执行if-else-if循环

时间:2015-06-01 14:13:31

标签: windows batch-file batch-processing spritebatch

我正在尝试在批处理编程中执行if-else循环,但它给了我意想不到的输出

代码:

echo 1. ICM
echo 2. Mini ICM
echo 3. SST
set /p ch = Enter the number(1 or 2 or 3) for Type of Environment :
echo.

IF "%ch%" EQU "1" ( 
set str1="ATTST"
) ELSE ( 
IF "%ch%" EQU "2" ( 
set str1="NBIST" 
) ELSE ( 
IF "%ch%" EQU "3" ( 
set str1="NBISST" 
) ELSE (
echo "Incorrect choice" 
    )))

echo "######################"



echo "Value of str1 is :"
echo "%str1%"

pause

我得到的输出是:

1. ICM
2. Mini ICM
3. SST
Enter the number(1 or 2 or 3) for

"Incorrect choice"
"######################"
"Value of str1 is :"
""
Press any key to continue . . .

任何人都可以帮助我,我错了吗?

4 个答案:

答案 0 :(得分:1)

我建议采用不同的方法:

:again
set /p "ch=Enter the number(1 or 2 or 3) for Type of Environment : "
set "str1="
IF "%ch%" EQU "1" set str1="ATTST"
IF "%ch%" EQU "2" set str1="NBIST" 
IF "%ch%" EQU "3" set str1="NBISST" 
if not defined str1 echo "Incorrect choice" & goto :again
echo value is %str1%

另外,你应该看看choice /?

答案 1 :(得分:0)

你有一个额外的空间:

set /p ch = Enter the number(1 or 2 or 3) for Type of Environment :
         ^

实际上很傻,cmd会创建一个名为ch[space]的env var:

C:\Users\marc>set /p ch = foo
foobar

C:\Users\marc>echo %ch%
%ch%

C:\Users\marc>echo %ch %
bar

答案 2 :(得分:0)

命令行将创建一个名为“ch”的变量,因为你有空格。

您应该使用"set /p ch=Enter the number(1 or 2 or 3) for Type of Environment :"

答案 3 :(得分:0)

您也可以使用更简单的array approach

@echo off
setlocal EnableDelayedExpansion

rem Define the list of "option=type" pairs
rem and create "option" and "type" arrays with it
set i=0
for %%a in ("ICM=ATTST" "Mini ICM=NBIST" "SST=NBISST") do (
   for /F "tokens=1,2 delims==" %%b in (%%a) do (
      set /A i+=1
      set "option[!i!]=%%b"
      set "type[!i!]=%%c"
   )
)

rem Show the menu
for /L %%i in (1,1,%i%) do (
   echo %%i. !option[%%i]!
)

:getOption
set /p ch=Enter the number (from 1 to %i%) for Type of Environment :
echo/

if defined option[%ch%] (
   set str1="!type[%ch%]!"
) ELSE (
   echo "Incorrect choice" 
   goto getOption
)

echo "######################"

echo "Value of str1 is :"
echo "%str1%"

pause