开发者

Batch if form with ( do ( in it?

What I'm basically trying to do is make 2 IF's wich could then resolve in 4 do's with action in. I'm guessing i'm doing something I may not, because i get an error:

) was not expected

Could anyone enlighten me on the form I need to use for implementing the DO in a result of the IF test? Thanks a lot.

Underneath you find the code i tried to run. (it's abstraction i.o code language)

if (logicaltest1) ( do (
if (logicaltest2) ( do (
action 1
echo something 1开发者_运维问答
)
) else ( do (
action 2
echo something 2
)
) else (
if (logicaltest) ( do (
action 3
echo something 3
)
)
) else ( do (
action 4
echo something 4
)
)

The four possibility's, in booleans for the 2 if's, just so i make myself clear: #t#t,#t#f,#f#t,#f#f (batch in dos)


In "DOS batch", "DO" is not used in "IF" statements, but rather is attached with "FOR".

On Windows 2000/XP/Vista/7, You may type IF /? for help. Similarly FOR /? would give you help on "FOR" statement.

Sample sketch:

if CONDITION1 (
  if CONDITION2 (
    echo CONDITION1 true, and CONDITION2 true
  ) else (
    echo CONDITION1 true, and CONDITION2 false
  )
) else (
  if CONDITION3 (
    echo CONDITION1 false, and CONDITION3 true
  ) else (
    echo CONDITION1 false, and CONDITION3 false
  )
)


Identing is the best way to find out what's wrong:

if (logicaltest1) (
    do (
        if (logicaltest2) (
            do (
                action 1
                echo something 1
            )
        ) else (
            do (
                action 2
                echo something 2
            )
        *)* (missing)
    *)* (missing)
) else (
    if (logicaltest) (
        do (
            action 3
            echo something 3
        )
    *)* (unexpected)
    ) else (
        do (
            action 4
            echo something 4
        )
    )
*)* (missing)

This should work.


For some reason I don't like nested IFs in batch files. When possible, I try to convert them so I always have only one level of indenting.

In case there are people who share such a disfavour, here's what could probably be done in this particular case:

set selector=0
if CONDITION1 set /A selector+=1
if CONDITION2 set /A selector+=2

rem Now we have only 4 possible cases for selector, from 0 to 3

if %selector% = 0 (
  ...
) else if %selector% = 1 (
  ...
) etc.

Of course nesting can give an advantage such that, when we have to execute some commands that only depend on CONDITION1, we do not have to repeat them, whereas with my approach it seems like we do. Still, I try to sort through such cases too, like using additional IFs like if /I selector lss 2 ... or something to that effect.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜