问题描述
我遇到一个简单的批处理脚本问题。参见:
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")
)
这里if分支中的if错误,因为没有定义变量TEST。但是如果没有定义变量TEST,则甚至不应该执行else分支!?
这是什么问题?
(我知道,这个代码可以工作,如果我离开else并在if语句下写,但是这个代码每次都执行。)
如何解决这个问题?
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。
推荐答案
Magoo的回答可以防止错误,但会导致错误而非数字。我认为使用和一个:
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")
)
这篇关于批量嵌套If语句错误,未定义变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!