1

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.

2 Answers 2

3

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")
)
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

but this will force an alphabetical comparison instead of numerical
@npocmaka :: true, but that won't be a problem unless the variable ever exceeds 9 or is negative. In all probability, and the absence of information to the contrary, the variable is likely to be set to 0 or 1 or not-set-at-all. Personally, I'd use a setting of nothing or something which allows if defined to work with run-time variables within a block statement.

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.