How to return an error code without closing the Command Prompt window?

Martin picture Martin · Feb 16, 2013 · Viewed 27.8k times · Source

I am writing a batch file which validates a couple of files. When one of the file isn't valid, I want the batch script to stop and return an error code >0. The code below seem to do the job, but calling "EXIT 2" closes the Command Prompt window in which the script was running.

:Validate
SETLOCAL
Validator %1
IF %ERRORLEVEL% GEQ 1 EXIT 2
ENDLOCAL

Any idea on how to return an error code without closing the Command Prompt?

Answer

Hans Passant picture Hans Passant · Feb 16, 2013

To get help for command prompt commands use their /? option. Exit /? shows:

Quits the CMD.EXE program (command interpreter) or the current batch script.

EXIT [/B] [exitCode]

/B specifies to exit the current batch script instead of CMD.EXE. If executed from outside a batch script, it will quit CMD.EXE

exitCode specifies a numeric number. if /B is specified, sets ERRORLEVEL that number. If quitting CMD.EXE, sets the process exit code with that number.

So you want

IF %ERRORLEVEL% GEQ 1 EXIT /B 2