Batch nested If statement error with not defined v

2019-08-09 14:07发布

问题:

I have a problem with a simple batch script. See:

SET TEST=
IF NOT DEFINED TEST ( 
    SET "TEST=1"
) ELSE (
    IF %TEST% LSS 1 ( SET "TEST=1")
)

Here the if in the else branch failes, because the variable TEST ist not defined. But the else branch even shouldn't been executed if the variable TEST isn't defined!? What is here the problem? (I knew, that this code would work, if I leave the else and write it under the if statement, but then this code get's executed every time.) How to solve this problem?

THX.

回答1:

Magoo's answer will prevent the error but it will lead to alphabetical comparison instead of numerical.I think it will be better to use delayed expansion and one additional if defined statement :

setlocal enableDelayedExpansion
SET "TEST="
IF NOT DEFINED TEST ( 
    SET "TEST=1"
) ELSE (
    if defined test IF !TEST! LSS 1 ( SET "TEST=1")
)


回答2:

The entire statement is parsed that is, examined for syntactic correctness before it is executed.

The parser finds

) ELSE (
    IF LSS 1 ( SET "TEST=1")
)

and objects because 1 is not a comparison operator.

) ELSE (
    IF "%TEST%" LSS "1" ( SET "TEST=1")
)

should fix the problem.