StrattonL
StrattonL

Reputation: 726

Batch file PAUSE requires two key presses to dismiss

I have the following code:

@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

Once the batch file has completed, I get the 'Press any key to continue' as expected. However, it requires 'any key' to be pressed twice before the batch file will end. It appears if I replace the following line:

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

with

if %errorLevel% == 1 goto error

I only get prompted once.

What is the issue?

Upvotes: 1

Views: 240

Answers (1)

Magoo
Magoo

Reputation: 79983

Unlike many languages, batch has no concept of the end of a "procedure" - it simply continues execution line-by-line until it reaches the end-of-file. Consequently, you need to goto :eof after completing the mainline, otherwise execution will continue through the subroutine code. :EOF is a predefined label understood by CMD to mean end of file. The colon is required.

When you call :label batch returns at the end-of-file (because the label is called) to the statement after the call - which is the color 4f within the error routine. Having just executed the pause just before returning, batch just charges on, line-by-line, until it once again encounters the pause - hence two prompt/response cycles.

Upvotes: 5

Related Questions