Batch check for empty user input

14,045

Solution 1

The usual way to check for an empty variable is compare if its "%value%" is "". However, in order for this to work you must delete the variable before the set /P, because if the user just press enter the previous value of the variabe is not modified:

set "var="
set /P var=
if "%var%" equ "" set "var=default value"

However, a simpler method is use if defined:

set "var="
set /P var=
if not defined var set "var=default value"

Previous method would not require delayed expansion.

As a corollary of previous description, you may get the same result this way:

set "var=default value"
set /P var=

Solution 2

You can check if the set /p operation was sucessful

set /p "var=prompt text?" || set "var=default value"

If you prefer the set / if, when you check for a value that can be empty or contain spaces, it is better to use quotes

if "%var%"=="" set "var=default value"

or, as a variable without content is not defined, you can check this case with

if not defined var set "var=default value"
Share:
14,045
Magier
Author by

Magier

Updated on June 15, 2022

Comments

  • Magier
    Magier almost 2 years

    I am struggling with a simple check if the user input was just empty (Enter) and in case set the variable to a new value... spend an hour but it does not work. Goal is to have the entered Value beginning with a backslash OR just an empty string if nothing was entered.

    Code:

    SET myTargetServerInstanceName=anyNOPEdummyValue
    SET /P myTargetServerInstanceName=Enter Target Server INSTANCE Name:    
    IF %myTargetServerInstanceName%==anyNOPEdummyValue SET myTargetServerInstanceName=
    IF NOT %myTargetServerInstanceName% == [] SET myTargetServerInstanceName=\%myTargetServerInstanceName%
    

    this results in error:

    SET was unexpected at this time.

  • Magier
    Magier over 8 years
    This indicated to the right direction. The following is working for me: IF [%myTargetServerInstanceName%] == [] SET myTargetServerInstanceName = \%myTargetServerInstanceName%