Search code examples
loopsbatch-fileenter

Batch: How to prevent looping code when holding enter


So iv'e made a little something here where there will be a list of numbers like 1-10 and whichever one you type (so far only 1) will show you information (so if i type and enter 1, it will go key1=key).

However, if I type 1 and click enter, it shows me that the Key1 = key which i intended but then if I hold down Enter key, it will keep looping the Key1=Key script and the homepage one, can this be stopped?

@echo off
:T
cls

echo Home Page
echo [1] NameA
echo.
echo [e] Exit

set /p word=
if "%word%"=="1" goto aaa
if "%word%"=="e" goto eee
goto T

:aaa
cls
echo Key1 = Key
pause
goto T

:eee
exit

Solution

  • @echo off
    setlocal
    
    :T
    cls
    
    echo Home Page
    echo [1] NameA
    echo.
    echo [e] Exit
    
    rem Undefine variable word before input.
    set "word="
    
    set /p "word="
    
    rem No input = word is not set a new value, thus not defined.
    if not defined word goto eee
    
    if "%word%"=="1" goto aaa
    if "%word%"=="e" goto eee
    goto T
    
    :aaa
    cls
    echo Key1 = Key
    pause
    goto T
    
    :eee
    exit
    

    If you only press Enter at the set /p prompt, variable word is not set (a new value). If word is undefined before the set /p input, then it will be undefined after, if you only press Enter.

    setlocal added to keep variables set local to the current script execution.