Home > front end >  How does the caller of subroutine in a CMD batch program obtain its exit code?
How does the caller of subroutine in a CMD batch program obtain its exit code?

Time:11-03

Supposing we have CMD batch script code like this:

CALL :SUB
REM DO SOMETHING WITH THE RESULT HERE (300)
EXIT

:SUB
EXIT /B 300

What variable or mechanism can be used to replace the REMarked like above to do one thing if the result of SUB was 300, and something else if not? I want to write in there something like this:

IF %RESULT% EQU 300 (
   ECHO Hi
) ELSE (
   ECHO Bye
)

Please correct me if I'm wrong but I think my mechanism (the conditional statement) here is fine, but what about the variable?

CodePudding user response:

This isn't intuitive as it might be in other programming languages, but the variable you want is %ERRORLEVEL%--the same variable used to record the results of other commands you might invoke in the batch script. Per Microsoft, the syntax of the exit command is:

exit [/b] [<exitcode>]

where exitcode, "Specifies a numeric number. If /b is specified, the ERRORLEVEL environment variable is set to that number. If you are quitting the command interpreter, the process exit code is set to that number."

So ultimately, you want to write,

IF %ERRORLEVEL% EQU 300 (
   ECHO Hi
) ELSE (
   ECHO Bye
)
  • Related