0

I have this batch file here and it doesn't run well. It says "( was unexpected at this time". Do you know why?

@ECHO OFF

SET A[0]=HOLA
SET A[1]=HELLO

SET I=0
:LOOP
IF DEFINED A[%I%] (
    ECHO %I%
    CALL SET B=%%A[%I%]%%
    CALL ECHO %%B%%
    IF %B% == HOLA (
        ECHO ES
    ) ELSE (
        ECHO EN
    )
    PAUSE
    SET /A I+=1
    GOTO :LOOP )

My expected output should be:

0
HOLA
ES
1
HELLO
EN
      

I don't understand why inside IF everything works different. Thanks in advance.

vicalomen
  • 1
  • 2
  • Is that what your actual code looks like? Please ensure that what we see is exactly how your batch file is really laid out. – Compo Aug 09 '22 at 20:08
  • 1
    Why is `SET I=0`, `:LOOP`, and `IF DEFINED A[%I%] (` all on the same line? – Darin Aug 09 '22 at 20:24
  • I have added as an edit, what I think your code is supposed to look like. If it does not, please change it and test it again. If it does, please remove the incorrectly formatted code, from your question. – Compo Aug 09 '22 at 20:39

1 Answers1

0
@ECHO OFF
SETLOCAL
    
SET "A[0]=HOLA"
SET "A[1]=HELLO"
    
SET /a I=0
:LOOP 
IF DEFINED A[%I%] (
 ECHO %I%
 CALL SET "B=%%A[%I%]%%"
 CALL ECHO %%B%%
 FOR /f "delims==" %%b IN ('set B') DO IF /i "%%b"=="B" (IF "%%c"=="HOLA" (SET "Same=Y") ELSE SET "Same=")
 IF DEFINED Same (
  ECHO ES
 ) ELSE (
  ECHO EN
 )
 rem PAUSE
 SET /A I+=1
 GOTO LOOP
)

GOTO :EOF

Use set "var=value" for setting string values - this avoids problems caused by trailing spaces. Don't assign a terminal \, Space or " - build pathnames from the elements - counterintuitively, it is likely to make the process easier. If the syntax set var="value" is used, then the quotes become part of the value assigned.

Your set syntax sets the value of the variable to the rest of the line.

Hence, the line including the label loop would be assigned to i.

if %B%... substitutes the value of B at the time the block was parsed. AT that time, B was not defined, so nothing is substituted, so the result is if == HOLA (... and cmd does not expect ( at this point and objects.

The complex line I've shown performs a set command on all variables that start b and assigns %%b to the variable name, %%c to its current value. There may be many variables that start B, so we need to select exactly B, and if B's value in %%c is HOLA then set Same, otherwise set Same to nothing, which means that Same will either be assigned, or not assigned respectively.

if defined operates on the current value of the variable, so same can be used safely to do the if processing.

BUT The clean way to do this is by using delayedexpansion.

Stephan's DELAYEDEXPANSION link

Magoo
  • 77,302
  • 8
  • 62
  • 84