0

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?

wiltomap
  • 3,933
  • 8
  • 37
  • 54
  • Your variable is not an [array](https://en.wikipedia.org/wiki/Array_data_structure), but a _list_. An [array variable](https://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990) should use square braquets this way: `array[1]=first element of array` – Aacini Apr 12 '18 at 13:57
  • Good point @Aacini! I've changed the question title. – wiltomap Apr 13 '18 at 07:11

2 Answers2

4

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.

Magoo
  • 77,302
  • 8
  • 62
  • 84
2

You get syntax errors at two points, where the commas does not what you want.

First problem is the if command. Also there is a better syntax (see below)
Second problem is the for command. There is a better syntax, too (see below)
Another possible problem is the set command; there is a safer (and recommended syntax (see below)

rem set table=
REM set table=geo1
 set "table=geo1,geo2,geo3"
if "%table%"=="" (goto :end)
for %%a in (%table%) do (
    echo Some commands with %%a...
)
:end
Stephan
  • 53,940
  • 10
  • 58
  • 91