我在shell (c:\windows\system32\cmd.exe)中执行脚本(.cmd)。我想要的是,当命令返回错误码时,.cmd文件结束执行,然后cmd.exe也结束执行,将错误码返回给调用它的那个文件。
我使用的是这样的东西:
C:\...\gacutil.exe /i C:\...\x.dll
if not errorlevel 0 (
echo Error registering C:\...\x.dll
exit %errorlevel%
)但这是行不通的。我尝试了退出/b,但在我看来是一样的。有什么想法吗?
发布于 2011-02-02 23:35:02
这会出现every now and then、IMHO退出和退出/b被破坏,因为它们只设置批处理文件使用的错误级别,但它们没有设置cmd.exe进程的退出代码。
如果批处理脚本正在执行错误级别检查,调用就足够了:
REM DoSomeAction.cmd
@echo off
call someprogram.exe
if errorlevel 1 exit /b
REM MainScript.cmd
@echo off
...
call DoSomeAction.cmd
if errorlevel 1 (
...
)但是,如果要使用&&或||语法(myscript.cmd&&someotherapp.exe),或者脚本是从程序而不是从另一个批处理文件启动的,则实际上需要设置进程退出代码(使用GetExitCodeProcess检索
@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使用“普通的”exit /b,然后用call myscript.cmd&&someotherapp.exe调用它确实有效,但您不能假设执行批处理文件的每个程序都会将进程创建为cmd.exe /c call yourscript.cmd
发布于 2011-02-02 00:05:36
这一切都与实际运行脚本的shell有关。当脚本执行时,它是在一个子subshell中运行的,所以调用exit只会退出该子subshell。但是,我认为如果使用CALL语句执行脚本,它将在该shell的上下文中执行,而不执行子shell。
因此,要执行该脚本,请使用
call <script.cmd>而且不仅仅是
<script.cmd>发布于 2014-06-26 03:45:27
您可以(Ab)使用GOTO's bug when it is with non existent label and negative conditional execution.In cmd.exe从批处理脚本模式切换到命令提示符模式,并可以退出:
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%
)https://stackoverflow.com/questions/4864670
复制相似问题