Batchfile: What's the best way to declare and use a boolean variable?
Solution 1
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.
Solution 2
set "condition="
and
set "condition=y"
where y
could be any string or numeric.
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
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
Solution 3
I suppose another option would be to use "1==1" as a truth value.
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:
set true=1==1
set false=1==0
set condition=%true%
:: some code
if %condition% (
%= Do something... =%
)
James Ko
Updated on December 18, 2020Comments
-
James Ko over 3 years
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
sincetrue
andfalse
are commands of their own.) -
jeb about 8 yearsThe answer of Magoo is better, as it also works inside of code blocks
-
Magoo about 7 years@AlexanderSchäl : More explanation.
%condition%
refers to the contents of the variablecondition
, soif defined %condition%
is enterpreted asif defined y
ifcondition
has the valuey