Batch (choice): ERRORLEVEL doesn't seem to work

168 Views Asked by At

I've written a batchfile and for hours I'm trying to fix a problem where a choice-command would cause the program to crash. The crash seems to occur during the first "if ERRORLEVEL"-command.

    choice /c EDCBA /n
if "%ERRORLEVEL%"=="5" (
    cls
    echo From which file should the first line be extracted?
    set /p ffe="> "
    echo set /p %gclvar%="<%ffe%">>codes/%current%.bati
    goto createblock
)
if "%ERRORLEVEL%"=="4" (
    echo set /p %gclvar%="> ">>codes/%current%.bati
    goto createblock
)
if "%ERRORLEVEL%"=="3" (
    cls
    echo Type in the operation.
    set /p op="> "
    echo set /a %gclvar%=%op%>>codes/%current%.bati
    goto createblock
)
if "%ERRORLEVEL%"=="2" (
    cls
    echo Type in the variable. (without "%")
    set /p var="> "
    echo set %gclvar%=%%var%%>>codes/%current%.bati
    goto createblock
)
if "%ERRORLEVEL%"=="1" goto createblock

The variable %gclarvar% is set by the user (no spaces used). The variable %current% is created with "%random%(block)". (:createblock exists)

1

There are 1 best solutions below

6
Jeff Zeitlin On

You’re treating ERRORLEVEL as a string; it’s a numeric.

Instead of IF "%ERRORLEVEL%" == "5" ... etc., which does a string comparison, use either

IF ERRORLEVEL 5 ... which tests ERRORLEVEL using a mechanism that has existed since more years ago than I care to admit to knowing about,

or

IF %ERRORLEVEL% EQU 5 ... which tests

See SS64 on CHOICE and SS64 on IF