Search code examples
batch-filewindows-scriptingspritebatch

Windows script doesn't work when user types in a whitespace


I'm writing a Windows script in batch. I have a problem with whitespaces in variables. When the user types in a space, the script breaks.

Here's the part of my script:

:package
SET /P packageName="Set package name:"
IF [%packageName%] EQU [] (
   ECHO Empty package name.
   goto package
) ELSE (
    set "packageName=%packageName: =%"
    echo %packageName%
    pause
)

Solution

  • This schould work:

    @ECHO OFF
    SETLOCAL ENABLEDELAYEDEXPANSION
    :package
    SET /P packageName="Set package name:"
    IF "%packageName%"=="" (
       ECHO Empty package name.
       goto package
    ) ELSE (
        set packageName=%packageName: =%
        echo !packageName!
        pause
    )
    

    There are two modifications to your script:

    • [%packageName%] EQU [] was replaced with "%packageName%"==""
    • I've added SETLOCAL ENABLEDELAYEDEXPANSION and changes echo %packageName% with echo !packageName!

    The second point is because you are changing the value of a variable inside an IF-construction. As the interpreter doesn't know what the new value will be at "compile" time, you have to evaluate the variable at run time. That's why you need SETLOCAL ENABLEDELAYEDEXPANSION and !...! instead of %...%. This forces the expansion at run time.