30

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?

Stephan
  • 53,940
  • 10
  • 58
  • 91
Martin
  • 39,309
  • 62
  • 192
  • 278

3 Answers3

61

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
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
4

You can use the pause command before calling exit.

If you don't like the message:

pause > nul

If you don't want to close the window, but just go back to the command prompt, you should use

EXIT /B
Pascal Belloncle
  • 11,184
  • 3
  • 56
  • 56
-2

Got the same issue. If you are writing a batch (windows shell script). 'cmd' should do it for you. this wont exit the batch and remains at the command prompt. Solved my problem. for ex: cd "\view\Flex Builder 3\gcc-mvn" set path="c:\view\jdk1.7.0_02\bin";"c:\view\apache-maven-3.0.5\bin";%path% mvn sonar:sonar cmd should remain at the prompt after the execution.

Hemakumar
  • 1
  • 1
  • 2
    This series of commands exits at the end because mvn is a batch file. You need to CALL mvn, not just execute it. If you don't use CALL when calling other batch files then you will never return from any batch file you call, the one called takes over and the original one no longer executes. Also, the CMD call at the end of your file is actually opening a NEW command processor, so you'd have two running instead of one. – David Jun 22 '15 at 12:11