Martin
Martin

Reputation: 40573

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

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?

Upvotes: 31

Views: 37418

Answers (3)

Pascal Belloncle
Pascal Belloncle

Reputation: 11389

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

Upvotes: 5

Hemakumar
Hemakumar

Reputation: 1

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.

Upvotes: -2

Hans Passant
Hans Passant

Reputation: 941217

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

Upvotes: 63

Related Questions