Batch file choice loop on unexpected input

522 Views Asked by At

So I have this choice:

echo.
echo  All done. What would you like to do next?
echo  1. Open output folder
echo  2. Exit
echo.

set /p Choose=" Select 1 or 2 and press Enter: "

if '%Choose%'==1 goto show
if '%Choose%'==2 goto end

The problem is, this script detect any other choice other than 2 as 1, which is not how I want it. Instead, I want it to loop back to choice on unexpected input. The closest thing the internet told me is:

if '%Choose%'NEQ 1 if '%Choose%'NEQ 2 goto choice

But this goes to choice on ANY input, even 1 or 2.

2

There are 2 best solutions below

1
Magoo On BEST ANSWER

Both sides of an if must be identical for == to become true. You've single-quoted the first, so you must single-quote the second. Actually, double-quote " both sides for safety. If both if statements fail, then the choice made is neither, so goto your first echo. Speaking of choice - you should look that up as another way to get the job done. Plenty of examples on SO - just use the search box in the top line

0
Mofi On

Use this code any the user can't press anything else than 1 or 2 (or Ctrl+C to break batch file execution) with immediate continuation of script processing after having hit key 1 or 2.

@echo off
echo/
echo  All done. What would you like to do next?
echo/
echo  1. Open output folder
echo  2. Exit
echo/
%SystemRoot%\System32\choice.exe /C 12 /N /M "Select 1 or 2: "
if errorlevel 2 goto :EOF

rem Code to run on open output folder.
echo Use selected 1.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

  • choice /?
  • echo /?
  • if /?
  • goto /?
  • rem /?

Read also the Microsoft support article Testing for a Specific Error Level in Batch Files why it is here enough to use only if errorlevel 2 goto :EOF as the only remaining option is that errorlevel has value 1 after execution of choice.

And read also DosTips forum topic ECHO. FAILS to give text or blank line - Instead use ECHO/ why it is better to use echo/ instead of echo. to output an empty line.

Read also: