【问题标题】:Batch file PAUSE requires two key presses to dismiss批处理文件暂停需要两次按键才能解除
【发布时间】:2014-06-19 23:24:04
【问题描述】:

我有以下代码:

@echo off
set scriptTitle=Mode Changer
title %scriptTitle%



rem Take Details
set /p machine=Enter machine name:%=%
echo. %machine%
set /p rMSNewMode=Mode (t/l):%=%
echo. %rMSNewMode%

rem Perform Task
cls

rem Check machine existence
ping %machine% -n 1
if %errorLevel% == 1 call:error "The specified machine (%machine%) could not be located."


:error
color 4f
title ERROR: %scriptTitle%
cls
echo. The following error has occurred:
echo.
echo. %~1
echo.
pause
goto EOF

批处理文件完成后,我按预期得到“按任意键继续”。但是,它需要在批处理文件结束之前按两次“任意键”。如果我替换以下行,就会出现:

if %errorLevel% == 1 call:error "The specified machine (%machine%) could not be located."

if %errorLevel% == 1 goto error

我只收到一次提示。

有什么问题?

【问题讨论】:

    标签: windows batch-file scripting


    【解决方案1】:

    与许多语言不同,批处理没有“过程”结尾的概念 - 它只是逐行继续执行,直到到达文件结尾。因此,您需要在完成主线后goto :eof,否则将通过子程序代码继续执行。 :EOF 是一个预定义标签,CMD 理解为表示 end of file。冒号是必需的

    当您 call :label 批处理在文件末尾(因为标签是 called)返回到 call 之后的语句时 - 这是 error 例程中的 color 4f。在返回之前刚刚执行了pause,批处理只是逐行充电,直到它再次遇到pause - 因此有两个提示/响应周期。

    【讨论】:

    • +1,但冒号是必需的CALL,否则它会在当前查找批处理文件而不是标签脚本。使用GOTO 时不需要冒号,除非使用隐式:EOF 标签。我更喜欢使用EXIT /B 而不是GOTO :EOF,但它们在功能上是等效的。
    • @dbenham:非常正确。固定的。这是goto :label,其中冒号是可选的(恕我直言,最好省略)。很好的发现!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-24
    • 1970-01-01
    • 2022-08-19
    • 2019-11-06
    • 1970-01-01
    • 1970-01-01
    • 2012-06-11
    相关资源
    最近更新 更多