Revilo February 2016

Batch nested If statement error with not defined variables

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.

Answers


Magoo February 2016

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.


npocmaka February 2016

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")
)

Post Status

Asked in February 2016
Viewed 1,959 times
Voted 9
Answered 2 times

Search




Leave an answer