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

39,517

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... =%
)
Share:
39,517
James Ko
Author by

James Ko

Updated on December 18, 2020

Comments

  • James Ko
    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 since true and false are commands of their own.)

  • jeb
    jeb about 8 years
    The answer of Magoo is better, as it also works inside of code blocks
  • Magoo
    Magoo about 7 years
    @AlexanderSchäl : More explanation. %condition% refers to the contents of the variable condition, so if defined %condition% is enterpreted as if defined y if condition has the value y