Check if a variable is defined
The
if
statement has a
defined
option which allows to check if a variable has been defined. It is almost equivalent to
if [%var%] == []
with the exception if the value of the variable consists of spaces, the
defined
version does not throw an error:
@echo off
set var=baz
set empty=
set "space= "
if defined var ( echo var is defined) else ( echo var is not defined)
rem var is defined
if defined undef ( echo undef is defined) else ( echo undef is not defined)
rem undef is not defined
if defined unset ( echo unset is defined) else ( echo unset is not defined)
rem unset is not defined
if defined space ( echo space is defined) else ( echo space is not defined)
rem space is defined
if [%var%] == [] ( echo var is empty) else ( echo var is not empty)
rem var is not empty
if [%undef%] == [] ( echo undef is empty) else ( echo undef is not empty)
rem undef is empty
if [%unset%] == [] ( echo unset is empty) else ( echo unset is not empty)
rem unset is empty
if [%space%] == [] ( echo space is empty) else ( echo space is not empty)
rem ] was unexpected at this time.
Localizing changes
Assignments of values to variables can be localized within a block that starts with the
setlocal
command and (optionally) ends with the
endlocal
command.
VAR=someValue
setlocal
VAR=changed
…
endlocal
rem value of VAR is someValue again
Replacing text in a variable
Note the typo (tow instead of two)
C:\> set numbers=one tow three
Correct the typo:
C:\> echo %numbers:tow=two%
one two three