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

James Ko picture James Ko · Feb 22, 2016 · Viewed 29.2k times · Source

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.)

Answer

Magoo picture Magoo · Feb 22, 2016
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