Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 882
Martin Avatar asked Feb 16 '13 01:02

Martin


People also ask

How do I close a batch file without closing the window?

Batch file processing ends when execution reaches the end of the batch file. The trick therefore is to use the goto command to jump to a label right before the end of the file, so that execution “falls off the end”.

What does @echo off mean in cmd?

echo off. When echo is turned off, the command prompt doesn't appear in the Command Prompt window. To display the command prompt again, type echo on. To prevent all commands in a batch file (including the echo off command) from displaying on the screen, on the first line of the batch file type: @echo off.

How do I find my return code using cmd?

To display the 0 or 1 return code values, you must type the pdadmin command, followed by either the AIX®, Linux®, or Solaris echo or the Windows errorlevel command: For AIX, Linux, and Solaris operating systems: # pdadmin_command # echo $?

How do you exit a script in cmd?

If quitting CMD. EXE, sets the process exit code no. To close an interactive command prompt, the keyboard shortcut ALT + F4 is an alternative to typing EXIT.


1 Answers

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 
like image 157
Hans Passant Avatar answered Oct 18 '22 20:10

Hans Passant