Every time I run this code:
%SystemRoot%\System32\choice.exe /C:12345 /M "1M(1)1F(2)2M(3)2N(4)3rd(5)"
IF ERRORLEVEL ==5 goto n3
IF ERRORLEVEL NEQ 5 echo incorrect try again
:n3
it gives me this error: NEQ was not expected at this time
what does this mean? I have tried different syntaxes but can't find anything online about what this means.
CodePudding user response:
errorlevel
is just a string, the same was as are socks
and banana
and 62
.
62
has a secondary meaning - it's a string but it's also a number.
errorlevel
also has a secondary meaning - it's a number that describes the result of executing a command.
Originally, we could use
if %zombies%==62 ...
which would mean if the *contents* of the variable "zombies" was exactly "62" (then do something)
OR we could use
if errorlevel n ...
which would mean if the current errorlevel
(ie the code returned from the last command [athough some commands do not alter the errorlevel
value]) was n
**OR greater than ** n
then do something.
This functionality remains.
Later, the comparison operator ==
was supplemented by {EQU NEQ GTR LSS GEQ LEQ} to enhance flexibility. Also by the else
clause to specify instructions whould the comparison not be evaluated to true
.
IF ERRORLEVEL ==5
compares the STRING ERRORLEVEL
to the STRING 5
. Since these two are different, it will not execute the echo
command
IF ERRORLEVEL NEQ 5
yields a syntax error because batch is expecting a number after errorlevel
or ==
(old syntax); but it finds NEQ
(new syntax in conflict with old).
IF %ERRORLEVEL% NEQ 5
would work as you apparently expect because %errorlevel%
retrieves the value of the current errorlevel
.
BUT there's a trap. %errorlevel%
retrieves the value of the user-defined variable errorlevel
and only goes on to the system-defined value if there is no user-defined variable errorlevel
.
Hence, of errorlevel
is 6
, then executing
ECHO %ERRORLEVEL%
SET "errorlevel=banana"
ECHO %ERRORLEVEL%
SET "errorlevel="
ECHO %ERRORLEVEL%
will report
6
banana
6
Hence, it's highly unusual to assign a value to errorlevel
or to the other magic variables like random
or cd
.