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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 19:28:33  来源:igfitidea点击:

Batchfile: What's the best way to declare and use a boolean variable?

windowsbatch-filecmdwindows-10command-prompt

提问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 $conditionsince trueand falseare commands of their own.)

有没有更好,更“正式”的方式来做到这一点?(例如,在 Bash 中,您可以执行if $conditiontrue并且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 ycould be any string or numeric.

wherey可以是任何字符串或数字。

This allows if definedand if not definedboth 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 trueand falsevalues:

当然,可以设置一些变量来保存truefalse值:

set true=1==1
set false=1==0

set condition=%true%

:: some code

if %condition% (
    %= Do something... =%
)