0

I've tried writing a simple batch file you can see below:

@echo off
title test file

:menu
set /p foo = Select option (1, 2, 3):
if foo == 1 goto one
if foo == 2 goto two
if foo == 3 goto three

:one
echo One!
goto menu

:two
echo Two!
goto menu

:three
echo Three!
goto menu

Writing any of the given options writes "One!" to screen and returns the user back to the menu label. I suspect the error is with the types of variable I am declaring, although I wouldn't know, since I'm new to Batch... Any help?

peki
  • 669
  • 7
  • 24
  • if you removed the whitespace before `=` from `set /p foo=Select..` and changed `foo == 1` with `%foo% equ 1` it will work, besides the concern that you still need to work around the fact that a person can still type any other character which you do not cater for at this point. `choice` has that built-in and only the characters defined can be selected – Gerhard Oct 16 '19 at 14:49
  • I suggest reading my answer on [How to stop Windows command interpreter from quitting batch file execution on an incorrect user input?](https://stackoverflow.com/a/49834019/3074564) It explains very detailed the disadvantages of `set /P` and how to get it safe and how easy a choice menu can be coded using command `choice` as demonstrated also by the answers already written here. – Mofi Oct 16 '19 at 14:59

2 Answers2

2

Don't use Set /P for known selections, use choice instead.

@Echo Off
Title test file

:menu
Choice /C 123 /M "Select option"
If ErrorLevel 3 GoTo three
If ErrorLevel 2 GoTo two

:one
Echo One!
GoTo menu

:two
Echo Two!
GoTo menu

:three
Echo Three!
GoTo menu

If you wanted to continue using the wrong command then something like this would be more like it:

@Echo Off
Title test file

:menu
Set "foo="
Set /P "foo=Select option [1,2,3]?"
If Not Defined foo GoTo menu
If "%foo%"=="1" GoTo one
If "%foo%"=="2" GoTo two
If "%foo%"=="3" GoTo three
GoTo menu

:one
Echo One!
GoTo menu

:two
Echo Two!
GoTo menu

:three
Echo Three!
GoTo menu
Compo
  • 36,585
  • 5
  • 27
  • 39
1

NOTE!! Do not mark my answer as correct as it is almost an exact duplicate of the other answer on here, it is simply an opinion on usage.

Anyway, as an addition to @compo's answer, which is 100% correct, I typically shorten it by not using if errorlevel and just goto directly.

@echo off
title test file

:menu
choice /C 123 /M "Select option"
goto label%errorlevel%

:label1
echo One!
goto menu

:label2
echo Two!
goto menu

:label3
echo three!
goto menu
Gerhard
  • 22,678
  • 7
  • 27
  • 43