|Meaningful Return Code|
At times you may need to worry about the return code of a batch program as some wrapping process needs to determine successful completion, for example you may wish to do this if you are running a batch file via a command processor invoked with the "ExeCa" command. Generally a return code of 0 is used to indicate success.
|Method 1 - Use Always Work/Fail Commands|
This method is useful where you only have two states (success and failure), a return code of zero indicates success and anything else indicates failure:
goto ExitRcError ... :ExitRc0 set SetRc=echo GOOD (this will always work) goto ExitWithRc :ExitRcError set SetRc=.\NoSuchExeToSetRc.EXE (this will never work) goto ExitWithRc :ExitWithRc %SetRc% >nul 2>&1
The code above runs one of two commands, one which will always work and so generate a return code of zero or one which can never succeed and so always returns a non-zero RC.
There must be no other statements (even a "REM") after the last line or the return code will be changed (idiots, they're everywhere...)!
|Method 2 - EXIT command|
The exit exit command has some parameters. I'm not sure which operating system first got them, so you may want to be wary if you need to support older operating systems. This approach has another major advantage if your invoking process needs to support other return conditions (for example success, failure and warning) as specific return codes can be set.
goto ExitRc123 ... :ExitRc0 @rem exit /B 0 exit 0 :ExitRc123 @rem exit /B 123 exit 123
The command processor (CMD.EXE) doesn't pick up return codes from an exit with "/B" (idiots, they're everywhere...)! So you should drop the "/B" to exit the command processor instead (of the batch file).