gpt4 book ai didi

batch-file - 如何同时退出cmd文件和shell?

转载 作者:行者123 更新时间:2023-12-04 21:54:22 24 4
gpt4 key购买 nike

我正在 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%
)

但这行不通。我尝试使用 exit/b 但对我来说看起来一样。有什么想法吗?

最佳答案

出现了every now and then , 恕我直言 exit 和 exit/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

关于batch-file - 如何同时退出cmd文件和shell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4864670/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com