Search code examples
batch-filetestingis-empty

Check if list variable is empty in Windows batch


I have the program below (simplified).

The fact is that table variable can contain none, one or several string values:

set table=
REM set table=geo1
REM set table=geo1,geo2,geo3

if [%table%]==[] (goto :end)

for %%a in %table% do (

    REM Some commands...

)

:end

REM Some commands...

If table= or table=geo1, no problem. The program is behaving as wanted.

If table=geo1,geo2,geo3 (several values), the program is closing immediatly even with a pause command at the end.

Is there a simple way to check wether a variable is empty or not, being an array or a single string?


Solution

  • Your problem is that a comma, like space is a default separator, so cmd interprets

    if [%table%]==[] (goto :end)
    

    as (eg)

    if [geo1 geo2 geo3]==[] (goto :end)
    

    hence it sees geo2 where it's expecting a comparison operator, generates an error message and terminates the batch. If you are running directly from the prompt, you'd see the message.

    The way to determine whether a variable is set is

    if defined variablename .....
    

    or

    if not "%variablename%"=="" .....
    

    where "quoting a string containing separators" solves the problem with contained-spaces, the sae wy as it does for file/directorynames.