windows Batchfile:声明和使用布尔变量的最佳方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35544871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Batchfile: What's the best way to declare and use a boolean variable?
提问by James Ko
What's the best way to declare and use a boolean variable in Batch files? This is what I'm doing now:
在批处理文件中声明和使用布尔变量的最佳方法是什么?这就是我现在正在做的:
set "condition=true"
:: Some code that may change the condition
if %condition% == true (
:: Some work
)
Is there a better, more "formal" way to do this? (e.g. In Bash you can just do if $condition
since true
and false
are commands of their own.)
有没有更好,更“正式”的方式来做到这一点?(例如,在 Bash 中,您可以执行if $condition
,true
并且false
是它们自己的命令。)
采纳答案by James Ko
I'm sticking with my original answer for the time being:
我暂时坚持我原来的答案:
set "condition=true"
:: Some code...
if "%condition%" == "true" (
%= Do something... =%
)
If anyone knows of a better way to do this, please answer this question and I'll gladly accept your answer.
如果有人知道更好的方法来做到这一点,请回答这个问题,我很乐意接受你的回答。
回答by Magoo
set "condition="
and
和
set "condition=y"
where y
could be any string or numeric.
wherey
可以是任何字符串或数字。
This allows if defined
and if not defined
both of which can be used within a block statement (a parenthesised sequence of statements) to interrogate the run-time status of the flag without needing enabledelayedexpansion
这允许if defined
并且if not defined
两者都可以在块语句(带括号的语句序列)中使用来询问标志的运行时状态,而无需enabledelayedexpansion
ie.
IE。
set "condition="
if defined condition (echo true) else (echo false)
set "condition=y"
if defined condition (echo true) else (echo false)
The first will echo false
, the second true
第一个会回声false
,第二个true
回答by timfoden
I suppose another option would be to use "1==1" as a truth value.
我想另一种选择是使用“1==1”作为真值。
Thus repeating the example:
因此重复这个例子:
set condition=1==1
:: some code
if %condition% (
%= Do something... =%
)
Of course it would be possible to set some variables to hold true
and false
values:
当然,可以设置一些变量来保存true
和false
值:
set true=1==1
set false=1==0
set condition=%true%
:: some code
if %condition% (
%= Do something... =%
)