Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

batch choice command with errorlevel isn't working

Tags:

batch-file

I am getting confused with the choice command. here is my code:

@echo off
:start
cls
echo yes or no?
Choice/c yn
if errorlevel 1 goto yes
if errorlevel 2 goto no
:yes
echo you pressed yes
pause
goto start
:no
echo you pressed no
pause
goto start

the problem is every time I get yes. I figured out if I used this:

set x=%errorlevel%

and then used

if %x%==1 goto yes
if %x%==2 goto no

and the script workes fine. Why is this? I think I remember reading something about checking errorlevel could actually set a new errorlevel if false, or something like that. A little help?


2 Answers

The construct if errorlevel n checks if the errorlevel is at least n. So if errorlevel is 4, then the tests if errorlevel 1 to if errorlevel 4, all of them, return true.

The way to do the test is go from higher errorlevel to lower errorlevel

if errorlevel 2 goto no
if errorlevel 1 goto yes
like image 196
MC ND Avatar answered Apr 14 '26 14:04

MC ND


You can use the syntax MC ND mentioned, or you use the more clearly syntax of

if %errorlevel%==1 goto yes
if %errorlevel%==2 goto no
like image 32
jeb Avatar answered Apr 14 '26 14:04

jeb