0

The following programm ignores the first input, will ask again and only then accept the input.

@echo off
SETLOCAL
IF EXIST C:\Windows\notepad.exe (
    :confirm
    SET /P confirm="overwrite? yn "
    echo entered: %confirm%
    IF /I "%confirm%"=="y" GOTO overwrite
    IF /I "%confirm%"=="n" GOTO no
    GOTO confirm
    :no
    echo You selected no.
    exit 1
    :overwrite
    echo You selected yes.
)

Entering y<ENTER>, y<ENTERY> will result in the output:

overwrite? yn y
entered:
overwrite? yn y
entered: y
You selected yes.

Entering y<ENTER>, n<ENTER> will result in the output:

overwrite? yn y
entered:
overwrite? yn n
entered: n
You selected no.

I start the programm with cmd /k input-test.cmd.

Removing the IF EXIST will remove that bug.

FlyingFoX
  • 3,379
  • 3
  • 32
  • 49

1 Answers1

1

you'd need delayed expansion.
And DON'T use gotos and Labels inside a code block! The goto confirm breaks your code block, so delayed expansion isn't applied any more (that's why it works the second time).

But with a slight change of your logic you don't need the code block at all:

@echo off
SETLOCAL
IF NOT EXIST C:\Windows\notepad.exe GOTO :eof
:confirm
SET /P confirm="overwrite? yn "
echo entered: %confirm%
IF /I "%confirm%"=="y" GOTO overwrite
IF /I "%confirm%"=="n" GOTO no
GOTO confirm
:no
echo You selected no.
exit 1
:overwrite
echo You selected yes.

Also for such simple user questions, the choice command is far better suited than set /p. It does it's own errorhandling, so it reduces your code to:

@echo off
SETLOCAL
IF NOT EXIST C:\Windows\notepad.exe exit /b 2
choice /c YN /m overwrite?
IF errorlevel 2 goto no
if errorlevel 1 goto overwrite

:no
echo You selected no.
exit /b 1
:overwrite
echo You selected yes.
Stephan
  • 53,940
  • 10
  • 58
  • 91
  • The choice command looks interesting, but I couldn't find out on which platforms it is available. I am interested in running my script on Windows XP and on Windows CE 5 and 7, which uses PocketCMD. – FlyingFoX Aug 28 '18 at 09:28
  • 1
    look [here](https://www.computerhope.com/choicehl.htm#availability) for availability. Note: there was a slight syntax change between XP and VISTA – Stephan Aug 28 '18 at 09:32