0

I am trying to execute if-else loop in batch programming, but it is giving me unexpected output

code:

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

Output I am getting is :

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

Can anyone help me, where I am wrong?

Infinite Recursion
  • 6,511
  • 28
  • 39
  • 51

4 Answers4

1

I suggest a different approach:

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

also, you should have a look at choice /?

Stephan
  • 53,940
  • 10
  • 58
  • 91
0

You have an extra space:

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

Silly as it is, cmd will create an env var named ch[space]:

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

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

C:\Users\marc>echo %ch %
bar
Marc B
  • 356,200
  • 43
  • 426
  • 500
0

Command line will create a variable called "ch " because you have space.

You should use "set /p ch=Enter the number(1 or 2 or 3) for Type of Environment :"

Wald
  • 1,063
  • 7
  • 13
0

You may also use the array approach, that is much simpler:

@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
Community
  • 1
  • 1
Aacini
  • 65,180
  • 12
  • 72
  • 108