Search code examples
filevariablesbatch-filecallspace

Spaces in user input


Script below is used to load a file created using input %Name% in another section of script. Code works fine for names without spaces, but in order to call a file with spaces in the %Name%, ex Test File, the user is required to input "Test File". The problem is, this sets the variable %Name% to "%Name%" rather than simply %Name%. Is there a better way to do this, or a method to remove "" in another step?

    :LoadError
    Echo INVALID NAME
    echo.
    echo.
    echo.
    echo.
    goto LoadSelect1
    :LoadSelect
    cls
    echo.
    echo.
    echo.
    echo.
    echo.
    goto LoadSelect1
    :LoadSelect1
    set /p Name=Enter character to load:
    cls
    if EXIST .\SaveFiles\%Name%_Savefile.bat goto Load
    goto LoadError
    :Load
    call:.\SaveFiles\%Name%_Savefile.bat
    cls

Solution

  • I'd use set /p Name=Enter character to load: cls set "name=%name:"=%" if EXIST ".\SaveFiles\%Name%_Savefile.bat" goto Load

    (and similarly for any mention of name)

    This will ensure that any quotes entered into Name are removed and quoting the entire filename makes sure that if you change your mind and have spaces in the pathname, it doesn't break the batch.

    Of course, it has its downsides too - characters with a special meaning to batch like ^% and a few others - rarely used in filenames - may present problems.