I have a batch file that runs a couple executables, and I want it to exit on success, but stop if the exit code <> 0. How do I do this?
To test for a specific ERRORLEVEL, use an IF command with the %ERRORLEVEL% variable. n.b. Some errors may return a negative number. If the batch file is being executed as a scheduled task, then exiting with an error code will be logged as a failed task. You can monitor the event log to discover those failures.
Error Level. The environmental variable %ERRORLEVEL% contains the return code of the last executed program or script.
batch-file Echo @Echo off @echo off prevents the prompt and contents of the batch file from being displayed, so that only the output is visible. The @ makes the output of the echo off command hidden as well.
%0 references argument 0 – the name of the batch file – always exactly as specified on command line or in another batch file.
Sounds like you'll want the "If Errorlevel" command. Assuming your executable returns a non-0 exit code on failure, you do something like:
myProgram.exe if errorlevel 1 goto somethingbad echo Success! exit :somethingbad echo Something Bad Happened.
Errorlevel checking is done as a greater-or-equal check, so any non-0 exit value will trigger the jump. Therefore, if you need to check for more than one specific exit value, you should check for the highest one first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With