Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if process returns 0 with batch file

I want to start a process with a batch file and if it returns nonzero, do something else. I need the correct syntax for that.

Something like this:

::x.bat  @set RetCode=My.exe @if %retcode% is nonzero    handleError.exe 

As a bonus, you may consider answering the following questions, please :)

  • How to write a compound statement with if?
  • If the application My.exe fails to start because some DLL is missing will my if work? If not, how can I detect that My.exe failed to start?
like image 757
Armen Tsirunyan Avatar asked Dec 15 '10 14:12

Armen Tsirunyan


People also ask

What is %~ n0 in batch file?

%0 is the name of the batch file. %~n0 Expands %0 to a file Name without file extension.

How do you check if a command is executed successfully in a batch file?

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.


1 Answers

ERRORLEVEL will contain the return code of the last command. Sadly you can only check >= for it.

Note specifically this line in the MSDN documentation for the If statement:

errorlevel Number

Specifies a true condition only if the previous program run by Cmd.exe returned an exit code equal to or greater than Number.

So to check for 0 you need to think outside the box:

IF ERRORLEVEL 1 GOTO errorHandling REM no error here, errolevel == 0 :errorHandling 

Or if you want to code error handling first:

IF NOT ERRORLEVEL 1 GOTO no_error REM errorhandling, errorlevel >= 1 :no_error 

Further information about BAT programming: http://www.ericphelps.com/batch/ Or more specific for Windows cmd: MSDN using batch files

like image 195
Eduard Wirch Avatar answered Sep 23 '22 05:09

Eduard Wirch