Whenever I want a boolean value in a batch script, I use the absence of a variable to mean FALSE, and the presence of a variable (any value) to mean TRUE.
To set the value to TRUE, simply define the variable with any value. I like to use a value of 1
:
set var=1
To set the value to FALSE, undefine the variable:
"set var="
Whenever I need to test the value, I simply use
if defined var (rem true conditional statements) else (rem false conditional statements)
Now, to allow for an optional parameter that sets upgrade to logical TRUE - Initialize the value to false, and then check your parameter list to see if an option exists, and if it does, set the value to TRUE. I recommend an option like /U
to mean upgrade. You don't say whether your script already has parameters. I'll assume you have 2 required parameters.
You should decide if your options come before or after your required parameters. The easiest is after. So if you have 2 required parameters, then the option, if present, would be in %3
@echo off
setlocal
:: Initialize default value to FALSE
set "upgrade="
:: Look for option
if /i %3 equ /U set upgrade=1
You can put your options in the front, but then your required argument values must be quoted if the value begins with /
. After processing an option, use SHIFT /1
to guarantee that your required parameters start with %1
@echo off
setlocal
:: Initialize default value to FALSE
set "upgrade="
:: Look for option
if /i %1 equ /U (
set upgrade=1
shift /1
)
:: Required parameters now start with %1, regardless whether the option was present.
You can extend the above methods to support multiple options by adding a :parseOptions
label, followed by multiple IF statements, one per option. Each time an option is discovered, simply SHIFT the parameters and GOTO :parseOptions
to look for the next option. If options are at the end, then use SHIFT /3
. If options are at the beginning, then SHIFT /1
. But the coding becomes tedious and error prone if there are a lot of options.
Take a look at Windows Bat file optional argument parsing for a convenient and powerful way to define many optional parameters. It provides a mechanism to specify the default value for each option. It may be a bit of overkill for a single option, but it is very helpful if you have a lot of options.
For an example of a script with many options, see getTimestamp.bat for time and date processing