0

i have a batch script like this:

@echo off
setlocal

some commands to set variable %equal%

if %equal%==no (
    some commands to set variable %equall% (including a call to a separate batch file)
    if %equall%==no (
        other commands (including a call to a separate batch file)
    )
) else (
    echo nothing new
)

endlocal
exit /b

But i getting this error (translated from spanish, so it can be innacurate): "(" was not expected at this moment on the first if sentence.

However, if i remove the inner if condition, it runs fine....

What am i missing?

kurokirasama
  • 737
  • 8
  • 31

2 Answers2

2

you've got a delayed expansion problem. The variable equall gets defined inside a code block, so %equall% is still not defined. That makes your line

if %equall%==no ( 

to be parsed as

if ==no (

which leads to the mentioned error "(" is unexpected at this time"

To correct it, enable delayed expansion with the setlocal enabledelayedexpansion command and use delayed expansion with ! syntax instead of % syntax:

setlocal enabledelayedexpansion
if 1==1 (
  set "var=hello"
  echo !var!
)

Also you should get used to use a better syntax with if (quoting both sides of the comparison):

if "%var%" == "value" ...

(or with delayed expansion: if "!var!% == "value") Even if the variable is empty, this gets parsed as:

if "" == "value" ...

which is perfectly valid syntax.

Community
  • 1
  • 1
Stephan
  • 53,940
  • 10
  • 58
  • 91
0

I used a workaround, that is to send everything inside the outer if to a label:

@echo off
setlocal

some commands to set variable %equal%

if %equal%==no (
    goto :label
) else (
    echo nothing new
)

endlocal
exit /b

:label
some commands to set variable %equall% (including a call to a separate batch file)
if %equall%==no (
    other commands (including a call to a separate batch file)
)
kurokirasama
  • 737
  • 8
  • 31