批量嵌套If语句错误,未定义变量 [英] Batch nested If statement error with not defined variables

查看:197
本文介绍了批量嵌套If语句错误,未定义变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一个简单的批处理脚本问题。参见:

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的回答可以防止错误,但会导致错误按字母顺序比较而非数字。我认为使用延迟扩展和一个附加的if语句

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语句错误,未定义变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆