Search code examples
batch-filecommand-line

How to exit a user input loop in batch?


Well I have a simple for loop to take user input and creat a file with this input, then ask for the next input and create "file2" etc., but I can't seem to figure out how my user can quit the loop with a certain input (maybe "exit" or "end").

setlocal enabledelayedexpansion
set x=1

:runName

set /p names="Enter header for file !x!:"

for %%a in (%names%) do (>>file!x!.txt (echo %%~a) set /a x+=1)

if !names!=end goto:eof else goto:runName

:eof

echo press any key to close pause>nul

Ps. Sorry for the poor formatting, I cant figure how to enter my code in the grey field from my phone and dont have a computer at the moment.


Solution

  • I'm not quite shure why the input prompt says header.
    Here is my best guess what you may have meant:

    @Echo off
    setlocal enabledelayedexpansion
    set x=1
    
    :runName
    Set "names="
    set /p names="Enter header for file%x%:"
    if not defined names goto :end
    if /I "%names%" Equ "end" goto :end
    (
    for %%a in (%names%) do (echo:%%~a)
    ) >file!x!.txt
    set /a x+=1
    goto :runName
    :end
    echo press any key to close
    pause>nul
    

    Running

    Enter header for file1:anton bertha caesar
    Enter header for file2:anchorage berlin
    Enter header for file3:END
    press any key to close
    

    File content

    > type file*.txt
    file1.txt
    anton
    bertha
    caesar
    
    file2.txt
    anchorage
    berlin