CMD Simulator
System Informationset

SET Command Guide - Display and Set Environment Variables in Windows

Learn how to use the set command to display, set, and manage environment variables in Windows Command Prompt. Includes syntax, PATH manipulation, and batch script examples.

Rojan Acharya··Updated Mar 17, 2026
Share

The set command is a Windows Command Prompt utility that displays, sets, or removes environment variables for the current session. Use set with no arguments to list all variables, set VAR=value to create or update a variable, or set VAR= to delete one. Environment variables control how programs and scripts behave.

Whether you're configuring build environments, passing data between batch script steps, customizing the command prompt, or troubleshooting PATH and other system settings, mastering the set command provides essential control over the command session environment. Developers and system administrators rely on set for scripting, automation, and environment configuration.

This comprehensive guide covers set syntax, displaying and setting variables, substring expansion, delayed expansion, practical examples, troubleshooting tips, related commands, and frequently asked questions. By the end, you'll confidently manage environment variables from the command line.

What Is the Set Command?

The set command manages environment variables—named values that persist for the duration of the Command Prompt session. Common variables include:

  • PATH – Directories searched when you run a command
  • TEMP and TMP – Temporary file locations
  • USERNAME – Current user name
  • COMPUTERNAME – Computer name
  • PROMPT – Command prompt appearance

Variables set with set are session-local; they do not persist after closing the window. For persistent variables, use setx or System Properties.

The command works in Command Prompt (CMD) and batch files. Available in all Windows versions. No Administrator privileges required for session variables.

Set Command Syntax

The basic syntax for the set command is:

set [variable=[string]]
set /a expression
set /p variable=[promptstring]

Parameters and Modes

ParameterDescription
variableName of the environment variable
stringValue to assign (omit to delete; use = alone to set empty)
/aArithmetic expression (e.g., set /a count+=1)
/pPrompt user for input and store in variable

Without arguments, set displays all variables. With variable= and no value, the variable is deleted. With variable=value, the variable is set.

Displaying Environment Variables

List All Variables

set

Displays all environment variables for the current session. Output is typically long; pipe to more: set | more.

Display a Specific Variable

set PATH
set USERNAME

Shows the variable name and value. If the variable does not exist, nothing is displayed.

Filter Variables by Prefix

set JAVA

Displays all variables whose names start with JAVA (e.g., JAVA_HOME, JAVA_OPTS). Useful for finding related variables.

Setting Environment Variables

Set a Simple Value

set MYVAR=Hello World
echo %MYVAR%

Creates or updates MYVAR. Use %MYVAR% to expand the value in commands.

Set with No Value (Delete)

set MYVAR=

Removes the variable from the session. The variable no longer exists.

Set Empty Value

set MYVAR=

Same as delete. To set an explicit empty string, use set MYVAR="" (varies by context).

Append to PATH

set PATH=%PATH%;C:\NewTool\bin

Appends a directory to PATH. The new path is available for the rest of the session.

Prepend to PATH

set PATH=C:\PriorityTool\bin;%PATH%

Adds a directory at the beginning of PATH so it is searched first.

Examples

Set Variable for Script

@echo off
set BUILD_DIR=C:\Build\Output
set CONFIG=Release
echo Building to %BUILD_DIR% with %CONFIG%

Variables make scripts configurable and readable.

Arithmetic with /a

set /a count=0
set /a count+=1
set /a result=10+20

/a evaluates numeric expressions. Supports +, -, *, /, %, and bitwise operators.

Prompt for User Input

set /p name=Enter your name:
echo Hello, %name%!

/p reads a line from the user and assigns it to the variable.

Conditional Variable

set DEBUG=
if "%1"=="debug" set DEBUG=1
if defined DEBUG echo Debug mode is on

Use if defined VAR to check existence; use if "%VAR%"=="" to check for empty.

Substring Expansion

set str=HelloWorld
echo %str:~0,5%
echo %str:~5%

%var:~start,length% extracts a substring. Omit length for "rest of string."

Use in Same Line

set VAR=value && echo %VAR%

Variables set on a line are available on the next line. For same-line use, enable delayed expansion: setlocal enabledelayedexpansion and use !VAR!.

Temporary Override

set OLD_PATH=%PATH%
set PATH=C:\CustomTool;%PATH%
mycommand
set PATH=%OLD_PATH%

Restore PATH after running a command with a modified PATH.

Batch Loop Counter

set count=0
for %%f in (*.txt) do (
  set /a count+=1
  echo Processing %%f
)
echo Processed %count% files

Note: In loops, use delayed expansion (setlocal enabledelayedexpansion and !count!) to see updated values.

Common Use Cases

  1. Build environment setup – Set JAVA_HOME, ANDROID_HOME, or other tool paths before running builds.

  2. Script configuration – Use variables for paths, modes, and options at the top of batch files.

  3. PATH modification – Temporarily add tool directories without changing system PATH.

  4. Pass data between script sections – Set variables in one part, use in another.

  5. User input – Use set /p to prompt for filenames, options, or credentials.

  6. Debugging – Echo variables to trace script flow and verify values.

  7. Conditional logic – Set flags (e.g., DEBUG=1) and branch with if defined.

  8. Date/time in variables – Use set datetime=%date% %time% for timestamps in logs.

  9. Temporary overrides – Change variables for one command, then restore.

  10. Multi-step workflows – Store intermediate results in variables for later steps.

  11. Localization – Set language or locale variables for scripts.

  12. Testing – Override production paths with test paths via variables.

Tips and Best Practices

  1. Use meaningful names – Prefer BUILD_DIR over X; avoid single letters except in loops.

  2. Quote values with spacesset MYVAR="C:\Program Files" to handle paths with spaces.

  3. Enable delayed expansion in loops – Use setlocal enabledelayedexpansion and !VAR! when variables change inside for/if blocks.

  4. Restore modified variables – Save PATH (or others) before changing; restore when done.

  5. Check before use – Use if defined VAR before expanding to avoid unexpected behavior.

  6. Avoid special characters – &, |, and ^ need escaping; keep values simple when possible.

  7. Document in scripts – Add comments explaining what each variable controls.

  8. Use setlocal/endlocal – Limit variable scope to avoid polluting the caller's environment.

  9. Prefer setx for persistence – Use set for session-only; use setx for permanent changes.

  10. Test with echoecho %VAR% to verify values during development.

  11. Handle empty variables – Use if "%VAR%"=="" for empty checks.

  12. Consider case – Variable names are case-insensitive; SET VAR and set var are the same.

Troubleshooting Common Issues

Variable not expanding in loop

Problem: %VAR% in a for loop shows the initial value, not updates.

Cause: Variable expansion happens when the line is parsed, before the loop runs.

Solution: Use delayed expansion: setlocal enabledelayedexpansion and !VAR! instead of %VAR%.

Prevention: Use delayed expansion in any script where variables change inside blocks.

Special characters break set

Problem: Values with &, |, ^, or % cause errors.

Cause: These characters have special meaning in CMD.

Solution: Escape with ^: set VAR=one ^& two. Or use quotes: set "VAR=one & two".

Prevention: Quote entire assignment: set "VAR=value with & symbols".

PATH changes not persisting

Problem: set PATH=... works but is gone after closing CMD.

Cause: set only changes the current session.

Solution: For persistence, use setx: setx PATH "%PATH%;C:\NewPath". Or add via System Properties > Environment Variables.

Prevention: Use set for temporary changes; use setx or GUI for permanent changes.

Variable contains unexpected value

Problem: %VAR% shows wrong or empty value.

Cause: Typo in name, variable not set, or expansion timing (e.g., in loop).

Solution: Run set VAR to verify. Enable delayed expansion if in a loop. Check for trailing spaces: set VAR=value (no space before =).

Prevention: Use set "VAR=value" to avoid trailing spaces; verify with echo.

set /a fails with large numbers

Problem: Arithmetic overflow or incorrect result.

Cause: CMD uses 32-bit signed integers; range is about ±2 billion.

Solution: Use PowerShell or another tool for large numbers. Or break calculation into steps.

Prevention: Stay within 32-bit range for set /a.

Related Commands

setx – Persistent Environment Variables

setx sets environment variables permanently (user or system). Use set for session-only; use setx when changes must persist across reboots and new sessions.

path – PATH Display and Set

path displays or sets the PATH variable. For PATH-specific operations, path is sometimes more convenient than set PATH=.

echo – Display and Variables

echo displays text and variable values. Use echo %VAR% to show variable contents. Essential for debugging set usage.

if – Conditional and defined

if defined VAR checks if a variable exists. if "%VAR%"=="" checks for empty. Use with set for conditional logic.

setlocal / endlocal – Scope

setlocal creates a scope; variables set after it are local. endlocal exits the scope. Use to avoid polluting the parent environment.

Frequently Asked Questions

What is the difference between set and setx?

set changes variables for the current CMD session only; changes are lost when the window closes. setx writes to the registry and makes changes permanent for future sessions. Use set for temporary overrides; use setx for persistent configuration.

How do I delete an environment variable with set?

Use set VAR= (variable name followed by equals with nothing after). This removes the variable from the current session. For permanent removal, use setx with an empty value or System Properties.

Why does my variable not update inside a for loop?

CMD expands %VAR% when the line is parsed, before the loop runs. Use delayed expansion: add setlocal enabledelayedexpansion and use !VAR! instead of %VAR% to get the current value each iteration.

Can I use set to add to PATH?

Yes: set PATH=%PATH%;C:\NewDirectory. This appends to PATH for the current session. For persistence, use setx, but be careful—setx PATH overwrites the whole PATH, so use setx PATH "%PATH%;C:\NewDirectory".

How do I prompt for user input?

Use set /p variable=Prompt text: . The user types a line and presses Enter; the value is stored in the variable. Example: set /p name=Enter name: .

What does set /a do?

/a evaluates an arithmetic expression. Example: set /a x=5+3 sets x to 8. Supports +, -, *, /, %, and bitwise operations. Useful for counters and calculations in batch scripts.

How do I check if a variable is set?

Use if defined VAR command to run a command only if VAR exists. Use if "%VAR%"=="" to check for empty. Use if not defined VAR for the opposite.

Can set variables include spaces?

Yes. Use quotes: set "MYVAR=value with spaces". The quotes prevent trailing spaces from being included. Always quote when values may have spaces.

Why does echo %VAR% show %VAR% literally?

The variable is not set, or there is a typo. Variable names are case-insensitive but must match exactly. Run set to list all variables and verify the name.

How do I use variables in the same line they are set?

By default, variables set on a line are not available until the next line. Enable delayed expansion: setlocal enabledelayedexpansion, then use !VAR! for expansion at execution time.

Does set work in PowerShell?

Set is a CMD command. In PowerShell, use $env:VAR = "value" for environment variables. To run set from PowerShell: cmd /c "set VAR=value" (but that runs in a child CMD, so the variable is not in PowerShell).

How do I append to a variable?

Use the variable in the new value: set VAR=%VAR% additional. For PATH: set PATH=%PATH%;C:\NewPath. The existing value is expanded and concatenated with the new part.

Quick Reference Card

CommandPurposeExample
setList all variablesDisplay environment
set VARDisplay one variableCheck value
set VAR=valueSet variableCreate or update
set VAR=Delete variableRemove from session
set /a x=1+2ArithmeticCalculations
set /p name=Prompt:User inputRead from user
set PATH=%PATH%;C:\NewAppend to PATHAdd directory
if defined VARCheck existenceConditional

Try the Set Command in Our Simulator

Practice the set command safely in our Windows Command Simulator. Run set, set VAR=value, and other examples in your browser.

Visit the Commands Reference for a full list of supported Windows CMD commands, including system and scripting utilities.

Summary

The set command displays and sets environment variables for the current CMD session. Use set to list all, set VAR=value to set, and set VAR= to delete. Use /a for arithmetic and /p for user input. Variables are session-local; use setx for persistence.

Master set for scripting, build configuration, PATH management, and environment customization. Combine with setlocal, if defined, and delayed expansion for robust batch scripts.