How-To Geek
How to use windows cmd environment variables.
Environment Variables can be set permanently for a specific user or system-wide, or they can be set temporarily for a single process.

Quick Links
How to add or modify an environment variable, how to remove an environment variable.
It is easy to add or modify an environment variable with Command Prompt (CMD), but removing one is much more complicated. Here are a few different ways you can do it.
First, you need to launch Command Prompt, or CMD, as an administrator . Click Start, type "cmd" into the search box, and then click "Run as Administrator."
Any user environment variable can be set or modified in a regular Command Prompt window, but changing system-wide environment variables requires an elevated Command Prompt.
There are two distinct ways to set environment variables.
Setting an Environment Variable Temporarily
The first uses the set command. Set defines an environment variable exclusively within the process in which it has been defined --- in other words, the variable only works in the window you have open or the script that contains it.
Here's an example: Let's say you want to create an environment variable named LifeAnswerVar and set the value to 42. The command would be
While that window is open, LifeAnswerVar will have the value 42.
When it is closed, the environment variable and its value are deleted.
The exact same method works if you want to temporarily modify an existing Windows system variable. All you need to do is substitute the system variable you want to change in place of LifeAnswerVar, and the value you want to assign in place of 42.
As an example, if you wanted to move the TMP folder to C:\Example Folder, you'd enter the command
The first line,
, shows the current value of TMP. The second line assigns TMP a new value. The third line confirms that it has changed.
Setting an Environment Variable Permanently
The second way uses setx. Setx defines Windows environment variables permanently. They persist between windows and between restarts, and are written to the Windows Registry . These environment variables can be defined for a specific user, or they can be defined for system-wide use.
The command
will create a new environment variable named ExVar1 and assign the value "Tomato" to it. The /m argument specifies that the new variable should be system-wide, not just for the current user.
Use the exact same command to modify an existing environment variable, substituting ExVar1 for the name of the variable you'd like to change.
If you use setx to modify a variable and set to view the value of the variable, set will not display the right value until a new Command Prompt window is opened.
If you want to add or modify a user environment variable, just omit the /m argument from the command.
Removing an environment variable is a bit harder than adding or modifying one.
As with adding a variable, any user environment variable can be deleted in a regular Command Prompt window, but deleting a system-wide environment variable requires an elevated Command Prompt.
Removing an Environment Variable Temporarily
If you want to temporarily remove an environment variable for the current process, like a script, PowerShell window, or Command Prompt window, you can use the set command. All you need to do is assign no value to the variable.
For example, what if you have the variable definition
in the system-wide environment variables, but wanted to ignore it for one particular process? You can type
into Command Prompt or include that line in your script. The variable will be set to nothing while the script executes or until you open a new Command Prompt window.
Removing an Environment Variable Permanently
Removing an environment variable permanently is a bit more complex --- you have to use
Reg is the command-line version of the Registry Editor. You should proceed with caution --- a typo could result in you accidentally deleting something important. It never hurts to back up the part of the registry you're editing , either.
The environment variables for individual users are stored in
. System-wide environment variables are stored elsewhere, in
Let's use the
example. The ExVar1 environment variable was defined system-wide, which means it is located in the HKEY_LOCAL_MACHINE directory rather than the HKEY_CURRENT_USER directory. Specifically, the path to the subkey is:
This path contains a space. Any time there is a space in a path entered in a command-line interface, you must use quotation marks around the path, otherwise, it is exceedingly likely that it will not execute correctly.
Now we need to use the
command to remove it. Keep in mind that you'll need to substitute your variable name for ExVar1 in the command below.
There is a lot there, so let's break it down a bit.
- reg delete --- defines the application (reg) and command (delete) we're using
- "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\" --- Tells reg delete where to look for the key
- /f --- Tells reg delete to delete the key without prompting for confirmation
- /v --- Tells reg delete that it will be given a specific subkey to delete
- ExVar1 --- The name of the subkey we want to delete
Deleting an environment variable for an individual user is exactly the same as deleting a system-wide variable, except the path will be different. If ExVar1 were a user environment variable, the command to delete it would be:
If the command to delete the environment variable was successful, you should see "The operation completed successfully" in the Command Prompt.
Any time you remove an environment variable like this, you need to restart explorer.exe. You can restart Explorer.exe manually , or you can just restart your entire computer . Either will work, and the changes should take effect immediately after the restart.
Related: How to List Environment Variables on Linux
Display, set, or remove CMD environment variables. Changes made with SET will remain only for the duration of the current CMD session.
Variable names are not case sensitive but the contents can be.
It is good practice to avoid using any delimiter characters (spaces, commas etc) in the variable name .
Delimiter characters can be used in the value if the complete assignment is surrounded with double quotes to prevent the delimiter being interpreted.
Any extra spaces around either the variable name or the string , will not be ignored, SET is not forgiving of extra spaces like many other scripting languages. So use SET alpha=beta , not SET alpha = beta
The first character of the name must not be numeric . It is a common practice to prefix variable names with either an undescore or a dollar sign _variable or $variable , these prefixes are not required but help to prevent any confusion with the standard built-in Windows Environment variables or any other other command strings.
The CMD shell will fail to read an environment variable if it contains more than 8,191 characters.
Display a variable:
In most contexts, surround the variable name with % 's and the variable's value will be used e.g. To display the value of the _department variable with the ECHO command: ECHO %_department% If the variable name is not found in the current environment then SET will set %ERRORLEVEL% to 1 . This can be detected using IF ERRORLEVEL ... Including extra characters can be useful to show any white space: ECHO [%_department% ] ECHO "%_department% " Type SET without parameters to display all the current environment variables. Type SET with a variable name to display that variable SET _department The SET command invoked with a string (and no equal sign) will display a wildcard list of all matching variables Display variables that begin with 'P': SET p Display variables that begin with an underscore SET _
Set a variable:
Example of storing a text string: C:\> SET _dept=Sales and Marketing C:\> set _ _dept=Sales and Marketing Set a variable that contains a redirection character, note the position of the quotes which are not saved: SET "_dept=Sales & Marketing" One variable can be based on another, but this is not dynamic E.g. C:\> set "xx=fish" C:\> set "msg=%xx% chips" C:\> set msg msg=fish chips C:\> set "xx=sausage" C:\> set msg msg=fish chips C:\> set "msg=%xx% chips" C:\> set msg msg=sausage chips Avoid starting variable names with a number, this will avoid the variable being mis-interpreted as a parameter %123_myvar% < > %1 23_myvar To display undocumented system variables: SET "
Values with Spaces - using Double Quotes
Although it is advisable, there is no requirement to add quotation marks when assigning a value that includes spaces: SET _variable=one two three For special characters like & surround the entire expression with quotation marks. The variable contents will not include the surrounding quotes: SET " _variable=one & two " n.b. if you only place quotation marks around the value, then those quotes will be stored: SET _variable= " one & two "
Variable names with spaces
A variable can contain spaces and also the variable name itself can contain spaces, therefore the following assignment: SET _var =MyText will create a variable called "_var " ← note the trailing space.
Prompt for user input
The /P switch allows you to set a variable equal to a line of input entered by the user. The Prompt string is displayed before the user input is read. @echo off Set /P _ans=Please enter Department: || Set _ans=NothingChosen :: remove &'s and quotes from the answer (via string replace ) Set _ans=%_ans:&=% Set _ans=%_ans:"=% If "%_ans%"=="NothingChosen" goto sub_error If /i "%_ans%"=="finance" goto sub_finance If /i "%_ans%"=="hr" goto sub_hr goto:eof :sub_finance echo You chose the finance dept goto:eof :sub_hr echo You chose the hr dept goto:eof :sub_error echo Nothing was chosen Both the Prompt string and the answer provided can be left empty. If the user does not enter anything (just presses return) then the variable will be unchanged and the errorlevel will be set to 1. The script above strips out any '&' and " characters but may still break if the string provided contains both. For user provided input, it is a good idea to fully sanitize any input string for potentially problematic characters (unicode/smart quotes etc). The CHOICE command is an alternative for user input, CHOICE accepts only one character/keypress, when selecting from a limited set of options it will be faster to use.
Echo a string with no trailing CR/LF
The standard ECHO command will always add a CR/LF to the end of each string displayed, returning the cursor to the start of the next line. SET /P does not do this, so it can be used to display a string. Feed a NUL character into SET /P like this, so it doesn’t wait for any user input: Set /P _scratch="This is a message to the user " <nul
Place the first line of a file into a variable:
Set /P _MyVar=<MyFilename.txt Echo %_MyVar% The second and any subsequent lines of text in the file will be discarded. In very early versions of CMD, any carriage returns/new lines (CR+LF) before the first line containing text were ignored.
Delete a variable
Type SET with just the variable name and an equals sign: SET _department= Better still, to be sure there is no trailing space after the = place the expression in parentheses or quotes: (SET _department=) or SET "_department="
Arithmetic expressions (SET /a)
Placing expressions in "quotes" is optional for simple arithmetic but required for any expression using logical operators. When refering to a variable in your expression, SET /A allows you to omit the %'s so _myvar instead of %_myvar% Any SET /A calculation that returns a fractional result will be rounded down to the nearest whole integer. The expression to be evaluated can include the following operators: For the Modulus operator use (%) on the command line, or in a batch script it must be doubled up to (%%) as below. This is to distinguish it from a FOR parameter. + Add set /a "_num=_num+5" += Add variable set /a "_num+=5" - Subtract set /a "_num=_num-5" -= Subtract variable set /a "_num-=5" * Multiply set /a "_num=_num*5" *= Multiply variable set /a "_num*=5" / Divide set /a "_num=_num/5" /= Divide variable set /a "_num/=5" %% Modulus set /a "_num=17%%5" %%= Modulus set /a "_num%%=5" ! Logical negation 0 (FALSE) ⇨ 1 (TRUE) and any non-zero value (TRUE) ⇨ 0 (FALSE) ~ Bitwise invert & AND set /a "_num=5&3" 0101 AND 0011 = 0001 (decimal 1) &= AND variable set /a "_num&=3" | OR set /a "_num=5|3" 0101 OR 0011 = 0111 (decimal 7) |= OR variable set /a "_num|=3" ^ XOR set /a "_num=5^3" 0101 XOR 0011 = 0110 (decimal 6) ^= XOR variable set /a "_num=^3" Shift . (sign bit ⇨ 0) An arithmetic shift. >> Right Shift . (Fills in the sign bit such that a negative number always remains negative.) Neither ShiftRight nor ShiftLeft will detect overflow. <<= Left Shift variable set /a "_num<<=2" >>= Right Shift variable set /a "_num>>=2" ( ) Parenthesis group expressions set /a "_num=(2+3)*5" , Commas separate expressions set /a "_num=2,_result=_num*5" If a variable name is specified as part of the expression, but is not defined in the current environment, then SET /a will use a value of 0. SET /A arithmetic shift operators do not detect overflow which can cause problems for any non-trivial math, e.g. the bitwise invert often incorrectly reverses the + / - sign of the result. See SET /a examples below and this forum thread for more. also see SetX , VarSearch and VarSubstring for more on variable manipulation. SET /A should work within the full range of 32 bit signed integer numbers (-2,147,483,648 through 2,147,483,647) but in practice for negative integers it will not go below -2,147,483,647 because the correct two's complement result 2,147,483,648 would cause a positive overflow. Examples: SET /A "_result=2+4" (=6) SET /A "_result=5" (=5) SET /A "_result += 5" (=10) SET /A "_result=2 << 3" (=16) { 2 Lsh 3 = binary 10 Lsh 3 = binary 10000 = decimal 16 } SET /A "_result=5 %% 2" (=1) { 5/2 = 2 + 2 remainder 1 = 1 } SET /A "_var1=_var2=_var3=10" (sets 3 variables to the same value - undocumented syntax.) SET /A will treat any character string in the expression as an environment variable name. This allows you to do arithmetic with environment variables without having to type any % signs to get the values. SET /A "_result=5 + _MyVar " Multiple calculations can be performed in one line, by separating each calculation with commas, for example: Set "_year=1999" Set /a "_century=_year/100, _next=_century+1" The numbers must all be within the range of 32 bit signed integer numbers (-2,147,483,648 through 2,147,483,647) to handle larger numbers use PowerShell or VBScript . You can also store a math expression in a variable and substitute in different values, rather like a macro . SET "_math=(#+6)*5" SET /A _result="%_math:#=4% Echo %_result% SET /A _result="%_math:#=10% Echo %_result%
Leading Zero will specify Octal
Numeric values are decimal numbers, unless prefixed by 0x for hexadecimal numbers, 0 for octal numbers. So 0x10 = 020 = 16 decimal The octal notation can be confusing - all numeric values that start with zeros are treated as octal but 08 and 09 are not valid octal digits. For example SET /a "_month=07 " will return the value 7, but SET /a "_month=09" will return an error.
Permanent changes
Changes made using the SET command are NOT permanent, they apply to the current CMD prompt only and remain only until the CMD window is closed. To permanently change a variable at the command line use SetX or with the GUI: Control Panel ➞ System ➞ Environment ➞ System/User Variables Changing a variable permanently with SetX will not affect any CMD prompt that is already open. Only new CMD prompts will get the new setting. You can of course use SetX in conjunction with SET to change both at the same time: Set _Library=T:\Library\ SetX _Library T:\Library\ /m
Change the environment for other sessions
Neither SET nor SetX will affect other CMD sessions that are already running on the machine . This as a good thing, particularly on multi-user machines, your scripts won’t have to contend with a dynamically changing environment while they are running. It is possible to add permanent environment variables to the registry ( HKCU\Environment ), but this is an undocumented (and likely unsupported) technique and still it will not take effect until the users next login. System environment variables can be found in the registry here: HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
The CALL SET syntax will expand any variables passed on the same line, which is useful if you need to set one variable based on the value of another variable. CALL SET can also evaluate a variable substring , the CALL page has more detail on this technique, though in many cases a faster to execute solution is to use Setlocal EnableDelayedExpansion .
Autoexec.bat
Any SET statement in c:\autoexec.bat will be parsed at boot time Variables set in this way are not available to 32 bit gui programs - they won’t appear in the control panel. They will appear at the CMD prompt. If autoexec.bat CALLS any secondary batch files, the additional batch files will NOT be parsed at boot. This behaviour can be useful on a dual boot PC.
Errorlevels
When CMD Command Extensions are enabled (the default): Errorlevel If the variable was successfully changed unchanged , typically this will be 0 but if a previous command set an errorlevel, that will be preserved (this is a bug). SET No variable found or invalid name. SET _var=value when _var name starts with "/" and not enclosed in quotes. SET /P Empty response from user. 1 SET /A Unbalanced parentheses 1073750988 SET /A Missing operand 1073750989 SET /A Syntax error 1073750990 SET /A Invalid number 1073750991 SET /A Number larger than 32-bits 1073750992 SET /A Division by zero 1073750993
SET is an internal command. If Command Extensions are disabled all SET commands are disabled other than simple assignments like: _variable=MyText
# I got my mind set on you # I got my mind set on you... - Rudy Clark ( James Ray / George Harrison )
Related commands
Syntax - VarSubstring Extract part of a variable (substring). Syntax - VarSearch Search & replace part of a variable. Syntax - Environment Variables - List of default variables. CALL - Evaluate environment variables. CHOICE - Accept keyboard input to a batch file. ENDLOCAL - End localisation of environment changes, use to return values. EXIT - Set a specific ERRORLEVEL. PATH - Display or set a search path for executable files. REG - Read or Set Registry values. SETLOCAL - Begin localisation of environment variable changes. SETX - Set an environment variable permanently. Parameters - get a full or partial pathname from a command line variable. StackOverflow - Storing a Newline in a variable. Equivalent PowerShell: Set-Variable - Set a variable and a value (set/sv). Equivalent PowerShell: Read-Host - Prompt for user input. Equivalent bash command (Linux): env - Display, set, or remove environment variables.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
set (environment variable)
- 9 contributors
Displays, sets, or removes cmd.exe environment variables. If used without parameters, set displays the current environment variable settings.
This command requires command extensions, which are enabled by default.
The set command can also run from the Windows Recovery Console, using different parameters. For more information, see Windows Recovery Environment (WinRE) .
If command extensions are enabled (the default) and you run set with a value, it displays all of the variables that begin with that value.
The characters < , > , | , & , and ^ are special command shell characters, and they must be preceded by the escape character ( ^ ) or enclosed in quotation marks when used in <string> (for example, "StringContaining&Symbol"). If you use quotation marks to enclose a string that contains one of the special characters, the quotation marks are set as part of the environment variable value.
Use environment variables to control the behavior of some batch files and programs and to control the way Windows and the MS-DOS subsystem appears and works. The set command is often used in the Autoexec.nt file to set environment variables.
If you use the set command without any parameters, the current environment settings are displayed. These settings usually include the COMSPEC and PATH environment variables, which are used to help find programs on disk. Two other environment variables used by Windows are PROMPT and DIRCMD .
If you specify values for <variable> and <string> , the specified <variable> value is added to the environment and <string> is associated with that variable. If the variable already exists in the environment, the new string value replaces the old string value.
If you specify only a variable and an equal sign (without <string> ) for the set command, the <string> value associated with the variable is cleared (as if the variable isn't there).
If you use the /a parameter, the following operators are supported, in descending order of precedence:
If you use logical ( && or || ) or modulus ( % ) operators, enclose the expression string in quotation marks. Any non-numeric strings in the expression are considered environment variable names, and their values are converted to numbers before they're processed. If you specify an environment variable name that isn't defined in the current environment, a value of zero is allotted, which allows you to perform arithmetic with environment variable values without using the % to retrieve a value.
If you run set /a from the command line outside of a command script, it displays the final value of the expression.
Numeric values are decimal numbers unless prefixed by 0× for hexadecimal numbers or 0 for octal numbers. Therefore, 0×12 is the same as 18, which is the same as 022.
Delayed environment variable expansion support is disabled by default, but you can enable or disable it by using cmd /v .
When creating batch files, you can use set to create variables, and then use them in the same way that you would use the numbered variables %0 through %9 . You can also use the variables %0 through %9 as input for set .
If you call a variable value from a batch file, enclose the value with percent signs ( % ). For example, if your batch program creates an environment variable named BAUD , you can use the string associated with BAUD as a replaceable parameter by typing %baud% at the command prompt.
To set the value TEST^1 for the environment variable named testVar , type:
The set command assigns everything that follows the equal sign (=) to the value of the variable. Therefore, if you type set testVar=TEST^1 , you'll get the following result, testVar=TEST1 .
To set the value TEST&1 for the environment variable testVar , type:
To set an environment variable named include so the string c:\directory is associated with it, type:
You can then use the string c:\directory in batch files by enclosing the name include with percent signs ( % ). For example, you can use dir %include% in a batch file to display the contents of the directory associated with the include environment variable. After this command is processed, the string c:\directory replaces %include% .
To use the set command in a batch program to add a new directory to the path environment variable, type:
To display a list of all of the environment variables that begin with the letter p , type:
To display a list of all of the environment variables on the current device, type:
Related links
- Command-Line Syntax Key
Submit and view feedback for
Additional resources

CommandWindows.com
- Net Services (Net)
- Network Services Shell (Netsh)
- TCP/IP networking tools
- Disk management with the Diskpart console
- File system utility- Fsutil
- Recovery Console
- Recovery Console- Commands
- Registry editor console
- Service Controller Command (SC)
- Scripts in the command line
- Server 2003 tools for XP
- Introduction to Batch files
- Branching and Looping with "If: and "Goto"
- Iterating and Looping with "For.., in...do"
- Variables and the "Set" command
- Shell command
- Vista command list
- Vista command line tips
- List of commands in Windows 7
- List of shell folders
- Vista/7 command line tips
- Windows 8 Command Line List and Reference
How variables are defined with the "set" command
In one sense, there are two categories of variables for the command line. Some might use the term "variable" for the placeholders or arguments %1, %2, ..%9 , that are used to represent user input in batch files. ( See the discussion on this page .) However, the term "variable" is normally reserved in command line usage for entities that are declared as environment variables with the "set" command. Note that this is a pretty primitive way to define variables. For example, there is no typing. Environment variables, including numbers, are stored as strings and operations with them have to take that into account. Variables are declared and given a value in a single statement using "set". .The syntax is: set some_variable = some_value Variable names are not case-sensitve and can consist of the usual alphanumeric and other common characters. Some characters are reserved and have to be escaped. They should be avoided. These include the symbols in Table II on this page . Also, since these are environment variables, their names should be enclosed in percent signs when used in references and expressions, e.g , %some_variable% . The percent signs are not used in the left side of the set statement that declares a variable.
Localizing variables
The declaration of a variable lasts as long as the present command window is open. If you are using a batch file that does not close its instance of the command window when the batch file terminates, any variables that the batch file declares remain. If you wish to localize a variable to a particular set of statements, use the "setlocal" and "endlocal" commands. Thus. to confine a variable declaration to a particular block of code, use: .... setlocal set some_variable = some_value ... some statements endlocal ...
Variables from user input
The "set" command can also accept input from a user as the value for a variable. The switch " /p " is used for this purpose. A batch file will wait for the user to enter a value after the statement set /p new_variable= When the user has entered the value, the script will continue. A message string to prompt for input can also be used. For example: set /p new_variable="Enter value " Note the space at the end of the prompt message. Otherwise, the prompt message and the user-entered value will run together on the screen. It works but it looks funny. The user may be tempted to hit the spacebar, which adds a leading space to the input value.
Arithmetic operations
The command line is not designed for handling mathematical functions but it is possible to do some very simple integer arithmetic with variables. A switch " /a " was added to the "set" command to allow for some basic functions. Primarily, the use is adding and subtracting. For example, it is possible to increment or decrement counters in a loop. In principle, it is also possible to do multiplication and division.but only whole numbers can be handled so the practical use is limited. Although variables are stored as strings, the command interpreter recognizes strings that contain only integers, allowing them to be used in arithmetic expressions. The syntax is set /a some_variable= {arithmetic expression} The four arithmetic operators are shown in Table I. (I have omitted a "modulus" operation, which uses the % sign in yet another way. In my opinion this just adds difficulty to an already quirky syntax. Using % in more than one sense can only confuse.)
Here is an example of a variable %counter% being incremented: set /a counter=%counter%+1 This can also be written as: set /a counter+=1
Variables in comparison statements in batch files
Variables are often used in comparisons in conditional statements in batch files. Some of the comparison operators that are used are given in Table I of the page on "If" statements . Because of the somewhat loose way that the command line treats variables, it is necessary to be careful when comparing variables. For strings, the safest way is to quote variables. For example: if "%variable1%" == "%variable2%" some_command
Back to top
- Privacy Policy
POPULAR PAGES
- The Command Line in Windows: Batch file basics
- More Powerful Batch Files- Branching with "If" statements
- The Command Prompt|Shell in Windows- Introduction
- More Powerful Batch Files Part II - Iterating with "For"
- Running VBScripts and JavaScripts from the command shell
/* steve jansen */
// another day in paradise hacking code and more, windows batch scripting: variables.
Mar 1 st , 2013 | Comments
- Part 1 – Getting Started
- Part 2 – Variables
- Part 3 – Return Codes
- Part 4 – stdin, stdout, stderr
- Part 5 – If/Then Conditionals
- Part 6 – Loops
- Part 7 – Functions
- Part 8 – Parsing Input
- Part 9 – Logging
- Part 10 – Advanced Tricks
Today we’ll cover variables, which are going to be necessary in any non-trivial batch programs. The syntax for variables can be a bit odd, so it will help to be able to understand a variable and how it’s being used.

Variable Declaration
DOS does not require declaration of variables. The value of undeclared/uninitialized variables is an empty string, or "" . Most people like this, as it reduces the amount of code to write. Personally, I’d like the option to require a variable is declared before it’s used, as this catches silly bugs like typos in variable names.
Variable Assignment
The SET command assigns a value to a variable.
NOTE: Do not use whitespace between the name and value; SET foo = bar will not work but SET foo=bar will work.
The /A switch supports arthimetic operations during assigments. This is a useful tool if you need to validated that user input is a numerical value.
A common convention is to use lowercase names for your script’s variables. System-wide variables, known as environmental variables, use uppercase names. These environmental describe where to find certain things in your system, such as %TEMP% which is path for temporary files. DOS is case insensitive, so this convention isn’t enforced but it’s a good idea to make your script’s easier to read and troubleshoot.
WARNING: SET will always overwrite (clobber) any existing variables. It’s a good idea to verify you aren’t overwriting a system-wide variable when writing a script. A quick ECHO %foo% will confirm that the variable foo isn’t an existing variable. For example, it might be tempting to name a variable “temp”, but, that would change the meaning of the widely used “%TEMP%” environmental varible. DOS includes some “dynamic” environmental variables that behave more like commands. These dynamic varibles include %DATE% , %RANDOM% , and %CD% . It would be a bad idea to overwrite these dynamic variables.
Reading the Value of a Variable
In most situations you can read the value of a variable by prefixing and postfixing the variable name with the % operator. The example below prints the current value of the variable foo to the console output.
There are some special situations in which variables do not use this % syntax. We’ll discuss these special cases later in this series.
Listing Existing Variables
The SET command with no arguments will list all variables for the current command prompt session. Most of these varaiables will be system-wide environmental variables, like %PATH% or %TEMP% .
NOTE: Calling SET will list all regular (static) variables for the current session. This listing excludes the dynamic environmental variables like %DATE% or %CD% . You can list these dynamic variables by viewing the end of the help text for SET, invoked by calling SET /?
Variable Scope (Global vs Local)
By default, variables are global to your entire command prompt session. Call the SETLOCAL command to make variables local to the scope of your script. After calling SETLOCAL , any variable assignments revert upon calling ENDLOCAL , calling EXIT , or when execution reaches the end of file (EOF) in your script.
Special Variables
There are a few special situations where variables work a bit differently. The arguments passed on the command line to your script are also variables, but, don’t use the %var% syntax. Rather, you read each argument using a single % with a digit 0-9, representing the ordinal position of the argument. You’ll see this same style used later with a hack to create functions/subroutines in batch scripts.
There is also a variable syntax using ! , like !var! . This is a special type of situation called delayed expansion. You’ll learn more about delayed expansion in when we discuss conditionals (if/then) and looping.
Command Line Arguments to Your Script
You can read the command line arguments passed to your script using a special syntax. The syntax is a single % character followed by the ordinal position of the argument from 0 – 9 . The zero ordinal argument is the name of the batch file itself. So the variable %0 in our script HelloWorld.cmd will be “HelloWorld.cmd”.
The command line argument variables are * %0 : the name of the script/program as called on the command line; always a non-empty value * %1 : the first command line argument; empty if no arguments were provided * %2 : the second command line argument; empty if a second argument wasn’t provided * …: * %9 : the ninth command line argument
NOTE: DOS does support more than 9 command line arguments, however, you cannot directly read the 10th argument of higher. This is because the special variable syntax doesn’t recognize %10 or higher. In fact, the shell reads %10 as postfix the %0 command line argument with the string “0”. Use the SHIFT command to pop the first argument from the list of arguments, which “shifts” all arguments one place to the left. For example, the the second argument shifts from position %2 to %1 , which then exposes the 10th argument as %9 . You will learn how to process a large number of arguments in a loop later in this series.
Tricks with Command Line Arguments
Command Line Arguments also support some really useful optional syntax to run quasi-macros on command line arguments that are file paths. These macros are called variable substitution support and can resolve the path, timestamp, or size of file that is a command line argument. The documentation for this super useful feature is a bit hard to find – run ‘FOR /?’ and page to the end of the output.
- %~I removes quotes from the first command line argument, which is super useful when working with arguments to file paths. You will need to quote any file paths, but, quoting a file path twice will cause a file not found error.
SET myvar=%~I
%~fI is the full path to the folder of the first command line argument
%~fsI is the same as above but the extra s option yields the DOS 8.3 short name path to the first command line argument (e.g., C:\PROGRA~1 is usually the 8.3 short name variant of C:\Program Files ). This can be helpful when using third party scripts or programs that don’t handle spaces in file paths.
%~dpI is the full path to the parent folder of the first command line argument. I use this trick in nearly every batch file I write to determine where the script file itself lives. The syntax SET parent=%~dp0 will put the path of the folder for the script file in the variable %parent% .
%~nxI is just the file name and file extension of the first command line argument. I also use this trick frequently to determine the name of the script at runtime. If I need to print messages to the user, I like to prefix the message with the script’s name, like ECHO %~n0: some message instead of ECHO some message . The prefixing helps the end user by knowing the output is from the script and not another program being called by the script. It may sound silly until you spend hours trying to track down an obtuse error message generated by a script. This is a nice piece of polish I picked up from the Unix/Linux world.
Some Final Polish
I always include these commands at the top of my batch scripts:
The SETLOCAL command ensures that I don’t clobber any existing variables after my script exits. The ENABLEEXTENSIONS argument turns on a very helpful feature called command processor extensions. Trust me, you want command processor extensions. I also store the name of the script (without the file extension) in a variable named %me% ; I use this variable as the prefix to any printed messages (e.g. ECHO %me%: some message ). I also store the parent path to the script in a variable named %parent% . I use this variable to make fully qualified filepaths to any other files in the same directory as our script.
<< Part 1 – Getting Started Part 3 – Return Codes >>
Stack Exchange Network
Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.
Super User is a question and answer site for computer enthusiasts and power users. It only takes a minute to sign up.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
How to set and use a variable from an array value in a DOS/Windows batch file
In a DOS/Windows batch file, how can I set/use a variable from an array and a loop index, such that I can produce output like what's shown below?
What I'm really trying to do is repeatedly call a program and pass a bunch of parameters, one of which is an array variable. If I replace the [%%i] on the line with call set, with [0], the output when that line is executed is "call set y=one" as expected. But if I use [%%i] to access the array element the output changes to "call set y=". I've tried so many combinations of ways to do this, and none produce the desired result :(
How can I set/use a variable from an array and a loop index?
You have the right idea with your code but your are missing some of the details required for it to work correctly.
The following will do what you want (test.cmd)
Example output:
- for should be for /l but it seems the /l is optional as it work without it.
- Your for loop end value should have been 2 not 3 .
- You declared setlocal enabledelayedexpansion correctly but did not replace % with ! where appropriate.
- You don't need call before set .
- You didn't end your script with endlocal so your variable will "leak" into the parent cmd shell.
Further Reading
- An A-Z Index of the Windows CMD command line | SS64.com
- Windows CMD Commands (categorized) - Windows CMD - SS64.com
- EnableDelayedExpansion - Windows CMD - SS64.com
- Endlocal - Local environment variables - Windows CMD - SS64.com
- For /l - Loop through a range of numbers - Windows CMD - SS64.com

- Thank you so much... that does indeed work. Now to study what you did and see if I can learn something. – funbotix Feb 4, 2022 at 23:34
- @funbotix: Why not mark as answer if the guy answered your question right? – Ricardo Bohner Feb 6, 2022 at 21:06
- Thanks... I intended to mark the answer as correct, but I had not yet figured out how to do that yet. Fortunately... Google had the answer to that question ;) Thanks @DavidPostill – funbotix Feb 7, 2022 at 5:11
You must log in to answer this question.
Not the answer you're looking for browse other questions tagged batch array ..
- The Overflow Blog
- Edge and beyond: How to meet the increasing demand for memory sponsored post
- AI is only as good as the data: Q&A with Satish Jayanthi of Coalesce
- Featured on Meta
- Changes to MSE deployment process may cause intermittent issues on November...
- Update: New Colors Launched
Hot Network Questions
- Story from Middle-earth about the events of "The Lord of the Rings" being a lie
- Gurobipy MILP model comes infeasible yet can't compute IIS because "the model is feasible"
- Is there any merit in the argument "this data processing is required for my business model so it is strictly necessary in terms of data protection"?
- How do I undo the result of the remap of ( to ()?
- Does Cartomancer's Hidden Ace require the imbued spell's components at the time of casting or imbuing?
- Should we encourage our 2-year old to give up his naps?
- Development board's charging unit in a custom PCB production
- What is the difference between PN- and PM- Differential pairs?
- cloth modifier for not conected mesh
- What happens if a DNS record points to non-controlled IP address?
- Apply function to all first arguments of a nested list of rules
- Can human body heat cause a mobile phone's battery to "run down at a faster rate"?
- Number of words with 8 letters using an alphabet of 3 consonants and 2 vowels with constraints
- Delta of Black formula vs numerical
- In an interview how do I find out about taking small unofficial breaks when things aren't busy?
- Is it correct to use the present participle to describe what something does rather than only describing/modifying its current state?
- Do you lose money if you don't use a plane ticket you won in a raffle?
- Adding simple Geomasking (Donut masking) feature using PyQGIS
- how to output the τεχνική symbol
- Does this 1978 code for a 6800 really clear ALL of memory?
- Why does this Greek Orthodox monastery in Israel fly the English flag?
- Is the requirement to accept refugees unconditional in international law, even in the case of a forced population transfer?
- Cut a ribbon with a minumum amount of cuts (Middle School Math)
- Is there a tailwind limit while in cruise?
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

- Batch Script Tutorial
- Batch Script - Home
- Batch Script - Overview
- Batch Script - Environment
- Batch Script - Commands
- Batch Script - Files
- Batch Script - Syntax
Batch Script - Variables
- Batch Script - Comments
- Batch Script - Strings
- Batch Script - Arrays
- Batch Script - Decision Making
- Batch Script - Operators
- Batch Script - DATE & TIME
- Batch Script - Input / Output
- Batch Script - Return Code
- Batch Script - Functions
- Batch Script - Process
- Batch Script - Aliases
- Batch Script - Devices
- Batch Script - Registry
- Batch Script - Network
- Batch Script - Printing
- Batch Script - Debugging
- Batch Script - Logging
- Batch Script Resources
- Batch Script - Quick Guide
- Batch Script - Useful Resources
- Batch Script - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
There are two types of variables in batch files. One is for parameters which can be passed when the batch file is called and the other is done via the set command.
Command Line Arguments
Batch scripts support the concept of command line arguments wherein arguments can be passed to the batch file when invoked. The arguments can be called from the batch files through the variables %1, %2, %3, and so on.
The following example shows a batch file which accepts 3 command line arguments and echo’s them to the command line screen.
If the above batch script is stored in a file called test.bat and we were to run the batch as
Following is a screenshot of how this would look in the command prompt when the batch file is executed.

The above command produces the following output.
If we were to run the batch as
The output would still remain the same as above. However, the fourth parameter would be ignored.
Set Command
The other way in which variables can be initialized is via the ‘set’ command. Following is the syntax of the set command.
variable-name is the name of the variable you want to set.
value is the value which needs to be set against the variable.
/A – This switch is used if the value needs to be numeric in nature.
The following example shows a simple way the set command can be used.
In the above code snippet, a variable called message is defined and set with the value of "Hello World".
To display the value of the variable, note that the variable needs to be enclosed in the % sign.
Working with Numeric Values
In batch script, it is also possible to define a variable to hold a numeric value. This can be done by using the /A switch.
The following code shows a simple way in which numeric values can be set with the /A switch.
We are first setting the value of 2 variables, a and b to 5 and 10 respectively.
We are adding those values and storing in the variable c.
Finally, we are displaying the value of the variable c.
The output of the above program would be 15.
All of the arithmetic operators work in batch files. The following example shows arithmetic operators can be used in batch files.
Local vs Global Variables
In any programming language, there is an option to mark variables as having some sort of scope, i.e. the section of code on which they can be accessed. Normally, variable having a global scope can be accessed anywhere from a program whereas local scoped variables have a defined boundary in which they can be accessed.
DOS scripting also has a definition for locally and globally scoped variables. By default, variables are global to your entire command prompt session. Call the SETLOCAL command to make variables local to the scope of your script. After calling SETLOCAL, any variable assignments revert upon calling ENDLOCAL, calling EXIT, or when execution reaches the end of file (EOF) in your script. The following example shows the difference when local and global variables are set in the script.
Few key things to note about the above program.
The ‘globalvar’ is defined with a global scope and is available throughout the entire script.
The ‘var‘ variable is defined in a local scope because it is enclosed between a ‘SETLOCAL’ and ‘ENDLOCAL’ block. Hence, this variable will be destroyed as soon the ‘ENDLOCAL’ statement is executed.
You will notice that the command echo %var% will not yield anything because after the ENDLOCAL statement, the ‘var’ variable will no longer exist.
Working with Environment Variables
If you have variables that would be used across batch files, then it is always preferable to use environment variables. Once the environment variable is defined, it can be accessed via the % sign. The following example shows how to see the JAVA_HOME defined on a system. The JAVA_HOME variable is a key component that is normally used by a wide variety of applications.
The output would show the JAVA_HOME directory which would depend from system to system. Following is an example of an output.
Kickstart Your Career
Get certified by completing the course
DoS - Variables
Step-by-step tutorial on how to define local global variables environment variables and reference prompt to read value and store numeric values with examples setx,set command in dos batch programming..
This post is about how to use for loop in DOS programming.
There are two ways to declare and store the values in variables. .
- Set Command
- Command-line arguments
How to declare and use variables in batch programming using the set command
variables are used to hold the values and strings. We can declare variables in batch programming using the SET keyword.
here is a syntax
- set is a keyword
- left side of = is treated as a variable and the right side of = is a value.
- There is no space before or after the = symbol
- variable is a valid string in batch
- value is a value stored and assigned to the variable
- options are optional by default, /A and /P are some of the options.
- Without options, variables are inferred as strings by default.
We can use it for variable declaration with the following options.
- /P - Prompt the value to read from the command line
- /A - treat the variable as a numeric value
Once a variable is declared, you can use the variable with %variable% syntax.
Please enable JavaScript
The variable value is an echo to the command line.
Here is an example of declaring and using the variable with the set command
How to prompt to read the value from the command line and store it in a variable
/p option to set a command, stop its execution and wait for the user to type the string and read the value and store it in a variable.
The output of the above code is
how to read and store numeric numbers in a variables batch programming?
/A option in the SET command allows you to treat the variable to store numeric values.
Here is an example to sum the numbers and print the result to the command line.
How to read command line parameters in DOS batch programming?
Like any programming language, DOS batch enables to reading of command-line arguments using %1, %2, etc.
Here is an example to read command-line arguments and printing to the command line.
running job.bat one two three four command outputs the below
Variable types and scopes in Dos batch programming
scopes are variable scope that exists in a period
Based on scopes, There are different variable types
- Session and global variables
These variables exist in the running session of the dos window. Set command is an example of this.
the variable name only exists in the running session of the dos command prompt. The variable will not exist after the dos window is closed or session execution is closed in the current user context.
- Machine-level environment variables
These are system or machine levels. variables declared with this exist in multiple sessions and users. setx command is used to store the variable with values permanently.
Here is an example
The above JAVA_HOME environment variable exists after the Command line session is closed or logged with different users.
- Local variables
local variables are used to the scope of the block. The variables declared with SETLOCAL and ENDLOCAL are called local variables.

Stack Exchange Network
Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It only takes a minute to sign up.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
How to assign variable to PROMPT_COMMAND
How can I increment a variable assigning its value to PROMPT_COMMAND variable?
Inside .bashrc I created variable a and assigned value to 0 and then added this
When I echo PROMPT_COMMAND it shows that it is empty.

- PROMPT_COMMAND is empty in your code because ((a++)) doesn't print anything, only increments a . – wjandrea May 22, 2018 at 16:18
It works with
after you open a new shell (or source .bashrc by calling . ~/.bashrc .

You must log in to answer this question.
Not the answer you're looking for browse other questions tagged bash prompt ..
- The Overflow Blog
- Edge and beyond: How to meet the increasing demand for memory sponsored post
- AI is only as good as the data: Q&A with Satish Jayanthi of Coalesce
- Featured on Meta
- Changes to MSE deployment process may cause intermittent issues on November...
- Update: New Colors Launched
- Ubuntu 23.10 is now on-topic!
- AI-generated content is not permitted on Ask Ubuntu
Hot Network Questions
- Did early imperial China have a "uniform, multilevel administrative bureaucracy" that the Romans did not?
- What does ざらんや mean?
- What stat would I use for a crossbow if I throw it rather than shooting it?
- Can human body heat cause a mobile phone's battery to "run down at a faster rate"?
- What evolutionary pressure would lead to parrots or crows developing human-tier intelligence?
- Why does GCC copy object for each comparison in `std::ranges::max`?
- Does Cartomancer's Hidden Ace require the imbued spell's components at the time of casting or imbuing?
- Cut a ribbon with a minumum amount of cuts (Middle School Math)
- What happens if a DNS record points to non-controlled IP address?
- Move a coin without touching it
- Why are sickbays so ridiculously ill-equipped for large-scale medical situations?
- Is the requirement to accept refugees unconditional in international law, even in the case of a forced population transfer?
- Apply function to all first arguments of a nested list of rules
- Does this 1978 code for a 6800 really clear ALL of memory?
- How to use Compile to optimize the performance of a function calculating the distance between two points?
- How does jet fuel not spill out upon disconnecting from the wing's intake?
- In an interview how do I find out about taking small unofficial breaks when things aren't busy?
- Shuffled binary numbers
- Bag of Holding Bomb but with mayonnaise?
- Why do strings in musical instruments have helical shape?
- Delta of Black formula vs numerical
- cloth modifier for not conected mesh
- Is there a tailwind limit while in cruise?
- Filter Across Multiple Row Labels in Pivot Table
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

IMAGES
VIDEO
COMMENTS
It looks like it should be simple: @echo off set location = "bob" echo We're working with "%location%" The output I get is the following: We're working with "" What's going on here? Why is my variable not being echo'd? batch-file cmd environment-variables Share Improve this question Follow edited Jan 3, 2021 at 3:37 Magoo 77.6k 8 63 86
. The first line, set TMP , shows the current value of TMP. The second line assigns TMP a new value. The third line confirms that it has changed. Setting an Environment Variable Permanently
" SET " =" SET /A "variable " SET /P ] SET " Key A new or existing environment variable name e.g. _num A text string to assign to the variable. /A Arithmetic expression see full details . /P Prompt for user input. Variable names are not case sensitive but the contents can be.
Syntax Examples Related links Displays, sets, or removes cmd.exe environment variables. If used without parameters, set displays the current environment variable settings. Note This command requires command extensions, which are enabled by default. The set command can also run from the Windows Recovery Console, using different parameters.
2 Answers Sorted by: 4 We can easily get the hostname/computer name through below command set host=%COMPUTERNAME% echo %host% Share Improve this answer Follow answered Mar 21, 2017 at 6:38 Rajesh Kumar Mehta 80 7 Add a comment 1 Try Using @echo off for /f "delims=" %%a in ('hostname') do @set HOST=%%a echo %HOST% PAUSE
Assign output of a program to a variable using a MS batch file (12 answers) Closed last year. Is it possible to set a statement's output of a batch file to a variable, for example: findstr testing > %VARIABLE% echo %VARIABLE% windows batch-file Share Improve this question Follow edited Feb 2, 2016 at 9:12 g t 7,297 7 51 85
1 how can I set the result of the following command to be a variable called model? wmic computersystem get model The output of this is: Model VPCF22L1E Note the extra blank line. Use the following batch file (test.cmd): @echo off for /f "usebackq skip=1" %%i in (`wmic computersystem get model`) do ( set model=%%i goto :done ) :done @echo %model%
12 Answers Sorted by: 518 One way is: application arg0 arg1 > temp.txt set /p VAR=<temp.txt Another is: for /f %%i in ('application arg0 arg1') do set VAR=%%i Note that the first % in %%i is used to escape the % after it and is needed when using the above code in a batch file rather than on the command line.
5 Answers Sorted by: 104 A method has already been devised, however this way you don't need a temp file. for /f "delims=" %%i in ('command') do set output=%%i
Variables from user input. The "set" command can also accept input from a user as the value for a variable. The switch " /p " is used for this purpose. A batch file will wait for the user to enter a value after the statement set /p new_variable= When the user has entered the value, the script will continue.
Variable Assignment The SET command assigns a value to a variable. SET foo=bar NOTE: Do not use whitespace between the name and value; SET foo = bar will not work but SET foo=bar will work. The /A switch supports arthimetic operations during assigments. This is a useful tool if you need to validated that user input is a numerical value.
16. I need to get a value in a registry key and store in a variable using a batch file. I wrote a basic command line to exemplify my logic (using echo instead of setting a variable): for /f "tokens=3 delims= " %%a in ('reg query "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v "LastUsedUsername" ^|findstr /ri "REG_SZ"') do echo ...
You didn't end your script with endlocal so your variable will "leak" into the parent cmd shell. Further Reading. An A-Z Index of the Windows CMD command line | SS64.com; Windows CMD Commands (categorized) - Windows CMD - SS64.com; ... Batch: Unable to assign an array to a variable. 2.
I then use (although I know I could use the | char I am trying to avoid it) the command C:\Users\xyz\AppData\Local\Temp>FINDSTR [:] path.txt>path2.txt which gives the output F : which is incredibly frustrating as I obviously just need the "F"/alphabetic char that would be in its position and store it in a variable.
Syntax set /A variable-name=value where, variable-name is the name of the variable you want to set. value is the value which needs to be set against the variable. /A - This switch is used if the value needs to be numeric in nature. The following example shows a simple way the set command can be used. Example
There are two ways to declare and store the values in variables. . Set Command Command-line arguments How to declare and use variables in batch programming using the set command
How can I increment a variable assigning its value to PROMPT_COMMAND variable? Inside .bashrc I created variable a and assigned value to 0 and then added this. a=0 PROMPT_COMMAND=`((a++))` When I echo PROMPT_COMMAND it shows that it is empty.