Search notes:

cmd.exe: variables

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.
Github repository about-cmd.exe, path: /variables/check-if-variable-is-defined.bat

Enabling delayed expansion

@setlocal enabledelayedexpansion

@set var_foo=This is the foo
@set var_bar=Here's a bar
@set var_baz=See you in baz

@set choose=bar

@echo !var_%choose%!
Github repository about-cmd.exe, path: /variables/expansion/enabledelayedexpansion.bat

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

Pseudo variables

Some variables store dynamic values:

Undocumented variables

Some variables are undocumented:
For %__CD__% and %__APPDIR__%, see the function RtlQueryEnvironmentVariable_U in ntdll.dll.

See also

Batch argument/parameter variable expansion
The special variables %1, %2 etc, %* and %0 in batch files.
Using the tilde (~) and the colon in variables.
Delayed variable expansion
%CmdCmdLine%

Index