开发者

How to exit a cmd file and the shell at the same time?

I'm executing an script (.cmd) inside a shell (c:\windows\system32\cmd.exe). What I want is that when a command returns an errorcode the .cmd file ends its execution and then cmd.exe also ends its executing returning the errorcode to the one that called it.

I'm using something like this:

C:\...\gacutil.exe /i C:\...\x.dll
if not errorlevel 0 (
    ech开发者_StackOverflowo Error registering C:\...\x.dll
    exit %errorlevel%
)

But this does not work. I tried with exit /b but looks the same to me. Any idea?


This comes up every now and then, IMHO exit and exit /b are broken since they only set the errorlevel used by batch files, but they do not set the exit code of the cmd.exe process.

If a batch script is doing the errorlevel checking, call is enough:

REM DoSomeAction.cmd
@echo off
call someprogram.exe
if errorlevel 1 exit /b 

REM MainScript.cmd
@echo off
...
call DoSomeAction.cmd
if errorlevel 1 (
  ...
)

But if you want to use && or || syntax (myscript.cmd&&someotherapp.exe) or your script is started from a program and not another batch file, you actually want to set the process exit code (Retrieved with GetExitCodeProcess in the parent process)

@echo off
call thiswillfail.exe 2>nul
if errorlevel 1 goto diewitherror
...
REM This code HAS to be at the end of the batch file
REM The next command just makes sure errorlevel is 0
verify>nul
:diewitherror
@%COMSPEC% /C exit %errorlevel% >nul

Using a "normal" exit /b and then calling it with call myscript.cmd&&someotherapp.exe does work, but you can't assume that every program that executes a batch file will create the process as cmd.exe /c call yourscript.cmd


It's all about the shell that's actually running the script. When a script executes it is run in a subshell, so calling exit just exits that subshell. However, I think that if you execute the script by using the call statement it will execute within the context of that shell and not execute a subshell.

So, to execute the script use

call <script.cmd>

and not just

<script.cmd>


You can (ab)use GOTO's bug when it is with non existent label and negative conditional execution.In this case the cmd.exe from batch script mode to command prompt mode and can be exited:

C:\...\gacutil.exe /i C:\...\x.dll
if not errorlevel 0 (
    echo Error registering C:\...\x.dll
    goto :no_such_label >nul 2>&1 || exit %errorlevel%
)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜