Batch nested If statement error with not defined variables

亡梦爱人 提交于 2019-12-24 13:58:08

问题


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.



来源:https://stackoverflow.com/questions/35267196/batch-nested-if-statement-error-with-not-defined-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!