Batch Variables
A variable in a batch file is a named piece of text. You create it with set, and you read it back by wrapping its name in percent signs: %name%. There are no types and no declarations. Every value is a string, even 42; only set /a (next lesson) treats a value as a number.
@echo off
set city=Lisbon
set year=2025
echo I visited %city% in %year%.I visited Lisbon in 2025.
The rules of set
The syntax is set name=value. Everything after the first =, up to the end of the line, becomes the value. That simple rule has two consequences that catch almost every beginner:
- Spaces are part of the name and the value.
set name = Adacreates a variable calledname(with a trailing space) whose value isAda(with a leading space). - Trailing spaces are kept. An invisible space at the end of the line ends up inside the value.
@echo off
set name = Ada
echo [%name%]
echo [%name %]
set color=blue
echo [%color%][]
[ Ada]
[blue ]
%name% is empty because no variable has exactly that name; %name % finds the one with the space. The square brackets make the trailing spaces of color visible.
The safe form: set "name=value"
Put quotes around the whole assignment. The quotes are not stored; they only mark where the value ends, so trailing spaces after the closing quote are ignored. Use this form by default:
@echo off
set "fruit=mango"
set "greeting=Hello, world"
echo [%fruit%]
echo [%greeting%]
set label="quoted value"
echo [%label%][mango]
[Hello, world]
["quoted value"]
Only the first two values are bracketed tightly: set "fruit=mango" ignored the spaces after the closing quote. In contrast, set label="quoted value" (quotes around the value only) stores the quote characters themselves, which is rarely what you want.
The quoted form also lets you store characters such as & or > safely (set "op=a & b"), although printing such a value needs care, because %op% is expanded before CMD looks for &. Special Characters & Escaping shows how to handle that.
Naming rules
- Names are case-insensitive:
%Total%,%total%and%TOTAL%are the same variable. - Use letters, digits and underscores, and don't start with a digit (
%1is an argument, not a variable). - Avoid the names of built-in variables such as
PATH,TEMP,USERNAMEorCDunless you mean to change them.
@echo off
set "Score=10"
echo %score% %SCORE% %sCoRe%10 10 10
Reading an undefined variable
In a batch file, an undefined %name% expands to nothing. (Typed directly at the interactive prompt, it stays as the literal text %name%; batch files and the prompt differ here.) A typo in a variable name therefore fails silently:
@echo off
set "user=ada"
echo Hello, %usr%!
if not defined usr echo usr is not defined
if defined user echo user is definedHello, !
usr is not defined
user is defined
if defined name (no percent signs) tests whether a variable exists, which is more robust than comparing its value with an empty string. You'll see more in Batch if.
Deleting a variable
set name= with nothing after the = removes the variable. There is no such thing as a defined-but-empty variable in CMD:
@echo off
set "temp_note=remember the milk"
echo before: [%temp_note%]
set "temp_note="
echo after: [%temp_note%]
if not defined temp_note echo temp_note no longer existsbefore: [remember the milk]
after: []
temp_note no longer exists
Listing variables
set with a prefix lists every variable whose name starts with that text, as name=value lines. This is handy for debugging a group of related variables:
@echo off
set "app_name=Tracker"
set "app_version=1.4"
set "app_port=8080"
set app_app_name=Tracker
app_port=8080
app_version=1.4
set on its own prints the whole environment, sorted by name. If no variable matches the prefix, set prints an error and sets the exit code to 1, which you can test with if errorlevel 1 (see Exit Codes & errorlevel).
Built-in (dynamic) variables
CMD provides some variables that are computed on every read. You don't set them; you just use them:
| Variable | Value |
|---|---|
%CD% |
the current directory |
%USERNAME%, %COMPUTERNAME% |
the user and machine names |
%USERPROFILE% |
the home folder, e.g. C:\Users\ada |
%TEMP% |
the user's temp folder |
%ERRORLEVEL% |
the exit code of the last command |
%RANDOM% |
a random number from 0 to 32767 |
%DATE%, %TIME% |
the current date and time (format depends on the region settings) |
%~dp0 |
the folder of the running batch file (see Arguments) |
@echo off
echo Folder: %CD%
echo User: %USERNAME%
echo Home: %USERPROFILE%Folder: C:\Users\learner
User: learner
Home: C:\Users\learner
These names are only "dynamic" while nobody has set a real variable with the same name. If a script does set CD=x, %CD% returns x from then on and no longer tracks the directory, so never assign to them.
Environment variables and scope
Every variable you set is an environment variable: it is copied into the environment of every program the script starts. Without precautions it also stays defined in the Command Prompt window after the script ends, which is a common source of confusing bugs when you run a script twice. The cure is setlocal at the top of the script, which makes all changes temporary:
C:\Users\ada>type demo.bat
@echo off
setlocal
set "draft=only inside the script"
C:\Users\ada>demo.bat
C:\Users\ada>echo [%draft%]
[%draft%]Without setlocal, the last line would print [only inside the script]. setlocal & Delayed Expansion covers this in depth.
Comparison with other shells
| Task | CMD | Bash | PowerShell |
|---|---|---|---|
| assign | set "x=5" |
x=5 |
$x = 5 |
| read | %x% |
$x |
$x |
| delete | set "x=" |
unset x |
Remove-Variable x |
| test existence | if defined x |
[[ -v x ]] |
Test-Path variable:x |
Learn more: Bash Variables, PowerShell Variables, set /a Arithmetic.
Test yourself
After set name = Ada, which expression prints Ada?
- %name%
- %name %
- %NAME%
- %name=%
Why is set "file=report.txt" preferred over set file=report.txt?
- It makes the variable read-only
- The quotes mark the end of the value, so stray trailing spaces are not stored
- It stores the quotes as part of the value
- It makes the variable local to the script
What does set "backup=" do?
- Sets backup to an empty string
- Deletes the variable backup
- Prints the value of backup
- Causes a syntax error