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?

2 Answers 2

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.

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

2 Comments

Thankz a lot!. How do i call a for loop variable (%%i) in delayed extension?
loop variables (%%i) can't be delayed. Its just %%i
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)
)

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.