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?

2
  • Your variable is not an array, but a list. An array variable should use square braquets this way: array[1]=first element of array Commented Apr 12, 2018 at 13:57
  • Good point @Aacini! I've changed the question title. Commented Apr 13, 2018 at 7:11

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.