0

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?

ShieldOfSalvation
  • 1,297
  • 16
  • 32
  • 1
    Please open a [command prompt](https://www.howtogeek.com/235101/), run `if /?` and read the output usage help. There can be used `IF ERRORLEVEL 300 (ECHO Exit code of SUB is greater or equal 300) ELSE ECHO Exit code of SUB is less than 300` or `IF NOT ERRORLEVEL 300 (ECHO Exit code of SUB is less than 300) ELSE ECHO Exit code of SUB is greater or equal 300` or `IF ERRORLEVEL 300 IF NOT ERRORLEVEL 301 ECHO Exit code of SUB is exactly 300`. The recommended syntax to evaluate the exit code of a command or executable works always anywhere in a batch file while other solutions do not. – Mofi Oct 28 '22 at 05:06
  • See also [single line with multiple commands using Windows batch file](https://stackoverflow.com/a/25344009/3074564). – Mofi Oct 28 '22 at 05:07

1 Answers1

0

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
)
Stephan
  • 53,940
  • 10
  • 58
  • 91
ShieldOfSalvation
  • 1,297
  • 16
  • 32