在批处理文件中声明和使用布尔变量的最佳方法是什么?这就是我现在正在做的事情:
set "condition=true"
:: Some code that may change the condition
if %condition% == true (
:: Some work
)
有没有更好、更“正式”的方式来做到这一点? (例如,在 Bash 中,您可以只执行
if $condition
,因为 true
和 false
是它们自己的命令。)
set "condition="
和
set "condition=y"
其中
y
可以是任何字符串或数字。
这允许
if defined
和 if not defined
两者都可以在块语句(带括号的语句序列)中使用,以询问标志的运行时状态,而不需要 enabledelayedexpansion
即。
set "condition="
if defined condition (echo true) else (echo false)
set "condition=y"
if defined condition (echo true) else (echo false)
第一个将回显
false
,第二个 true
我暂时坚持原来的答案:
set "condition=true"
:: Some code...
if "%condition%" == "true" (
%= Do something... =%
)
如果有人知道更好的方法来做到这一点,请回答这个问题,我很乐意接受你的答案。
我想另一种选择是使用“1==1”作为真值。
因此重复这个例子:
set condition=1==1
:: some code
if %condition% (
%= Do something... =%
)
当然可以设置一些变量来保存
true
和 false
值:
set true=1==1
set false=1==0
set condition=%true%
:: some code
if %condition% (
%= Do something... =%
)
这对我有用。我怀疑尝试包含引号会使事情变得复杂,但是当分配的值没有任何空格时,引号可能不是必需的。
set condition=true
:: Some code that may change the condition
set condition=false
if %condition%==true (
:: Some work
) ELSE (
:: Do something else
)
使用延迟扩展时,请谨慎使用布尔文字,例如
true=1 EQU 1
或 true=1==1
(请参阅 timfoden 的建议):
SET "true=1 EQU 1"
IF ... (
SET is_true=%true%
IF !is_true! (...)
) ^ ---> ( was unexpected at this time.