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 .


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.


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


Environment variables in windows/macos/linux, path , classpath , java_home, what are environment variables.

Environment variables are global system variables accessible by all the processes/users running under the Operating System (OS), such as Windows, macOS and Linux. Environment variables are useful to store system-wide values, for examples,

  • PATH : the most frequently-used environment variable, which stores a list of directories to search for executable programs.
  • OS : the operating system.
  • COMPUTENAME , USERNAME : stores the computer and current user name.
  • SystemRoot : the system root directory.
  • (Windows) HOMEDRIVE , HOMEPATH : Current user's home directory.

(Windows) Environment Variables

Environment Variables in Windows are NOT case-sensitive (because the legacy DOS is NOT case-sensitive). They are typically named in uppercase, with words joined with underscore ( _ ), e.g., JAVA_HOME .

Display Environment Variables and their Values

To list ALL the environment variables and their values, start a CMD and issue the command " set ", as follows,

Try issuing a " set " command on your system, and study the environment variables listed. Pay particular attention to the variable called PATH .

To display a particular variable, use command " set varname ", or " echo % varname % ":

Set/Unset/Change an Environment Variable for the "Current" CMD Session

To set (or change) a environment variable, use command " set varname = value ". There shall be no spaces before and after the '=' sign. To unset an environment variable, use " set varname = ", i.e., set it to an empty string.

For examples,

An environment variable set via the " set " command under CMD is a local , available to the current CMD session only. Try setting a variable, re-start CMD and look for the variable.

Using an Environment Variable

To reference a variable in Windows, use % varname % (with prefix and suffix of '%' ). For example, you can use the echo command to print the value of a variable in the form " echo % varname % ".

How to Add or Change an Environment Variable "Permanently"

To add/change an environment variable permanently in Windows (so that it is available to ALL the Windows' processes/users and stayed across boots):

  • Launch "Control Panel"
  • "System"
  • "Advanced system settings"
  • Switch to "Advanced" tab
  • "Environment variables"
  • Choose "System Variables" (for all users)
  • Choose "New"
  • Enter the variable "Name" and "Value". Instead of typing the "value" and making typo error, I suggest that you use "Browse Directory..." or "Browse File..." button to retrieve the desired directory or file.
  • Choose "Edit"
  • Enter the new "Value". Instead of typing the "value" and making typo error, I suggest that you use "Browse Directory..." or "Browse File..." button to retrieve the desired directory or file.

You need to RE-START CMD for the new setting to take effect!

To verify the new setting, launch CMD:

PATH Environment Variable in Windows

When you launch an executable program (with file extension of " .exe ", " .bat " or " .com ") from the CMD shell, Windows searches for the executable program in the current working directory , followed by all the directories listed in the PATH environment variable. If the program cannot be found in these directories, you will get the following error:

To list the current PATH , issue command:

How to Add a Directory to the PATH in Windows

To add a directory to the existing PATH in Windows:

  • Under "System Variables" (for all users), select "Path"
  • "Edit"
  • (For newer Windows 10) A table pops up showing the directories included in the current PATH setting ⇒ "New" ⇒ "Browse..." to select the desired directory to be added to the PATH (Don't type as you will make typo error!) ⇒ Click "Move Up" repeatedly to move it to the top ⇒ "OK" (Don't "Cancel") ⇒ "OK" ⇒ "OK".
  • (For older Windows) If you didn't see a pop-up table, it is time to change your computer.

You need to RE-START CMD for the new PATH setting to take effect!

  • Windows searches the current directory ( . ) before searching the PATH entries. (Unixes/macOS does not search the current directory, unless you include it in the PATH explicitly.)
  • Windows uses semicolon ( ; ) as the path separator; while Unixes/macOS uses colon ( : ).
  • If your directory name contains special characters such as space (strongly not recommended), enclosed it with double quotes.

(macOS/Linux) Environment Variables

Environment variables in macOS/Unixes are case-sensitive. Global environment variables (available to ALL processes) are named in uppercase, with words joined with underscore ( _ ), e.g., JAVA_HOME . Local variables (available to the current process only) are in lowercase.

Using Environment Variables in Bash Shell

Most of the Unixes (Ubuntu/macOS) use the so-called Bash shell . Under bash shell:

  • To list all the environment variables, use the command " env " (or " printenv "). You could also use " set " to list all the variables, including all local variables.
  • To reference a variable, use $ varname , with a prefix '$' (Windows uses % varname % ).
  • To print the value of a particular variable, use the command " echo $ varname ".
  • To set an environment variable, use the command " export varname=value ", which sets the variable and exports it to the global environment (available to other processes). Enclosed the value with double quotes if it contains spaces.
  • To set a local variable, use the command " varname = value " (or " set varname = value "). Local variable is available within this process only.
  • To unset a local variable, use command " varname = ", i.e., set to empty string (or " unset varname ").

How to Set an Environment Variable Permanently in Bash Shell

You can set an environment variable permanently by placing an export command in your Bash shell's startup script " ~/.bashrc " (or "~/.bash_profile ", or " ~/.profile ") of your home directory; or " /etc/profile " for system-wide operations. Take note that files beginning with dot ( . ) is hidden by default. To display hidden files, use command " ls -a " or " ls -al ".

For example, to add a directory to the PATH environment variable, add the following line at the end of "~/.bashrc " (or "~/.bash_profile ", or " ~/.profile "), where ~ denotes the home directory of the current user, or " /etc/profile " for ALL users.

(For Java) You can set the CLASSPATH environment variables by adding the following line. For example,

Take note that Bash shell uses colon ( : ) as the path separator; while windows use semicolon ( ; ).

To refresh the bash shell, issue a " source " command (or re-start the bash shell):

(Notes) For the older csh (C-shell) and ksh (Korn-shell)

  • Use " printenv " (or " env ") to list all the environment variables.
  • Use " setenv varname value " and " unsetenv varname " to set and unset an environment variable.
  • Use " set varname = value " and " unset varname " to set and unset a local variable for the current process.

PATH Environment Variable

Most of the Unixes and macOS use the so-called Bash Shell in the " Terminal ". When you launch an executable program (with file permission of executable ) in a Bash shell, the system searches the program in ALL the directories listed in the PATH . If the program cannot be found, you will get the following error:

Take note that the current directory ( . ) is not searched, unless it is included in the PATH . To run a program in the current directory, you need to include the current path ( ./ ), for example,

How to Add a Directory to the PATH in macOS/Linux

To add a directory to the existing PATH in macOS/Unixes, add the following line at the end of one of the startup scripts, such as "~/.bashrc ", " ~/.login " "~/.bash_profile ", " ~/.profile " (where ~ denotes the home directory of the current user) or " /etc/profile " for ALL users.

  • Unixes/macOS does not search the current directory ( . ), unless you include it explicitly in the PATH . In other words, to run a program in the current directory, you need to provide the directory ( ./ ), for example, ./myProgram You could include the current directory in the PATH , by adding this line in a startup script: // Append the current directory (.) in front of the existing PATH export PATH= . :$PATH (Windows searches the current directory ( . ) automatically before searching the PATH.)
  • Unixes/macOS uses colon ( : ) as the path separator; while Windows uses semicolon ( ; ).

Java Applications and the Environment Variables PATH , CLASSPATH , JAVA_HOME

Many problems in the installation and running of Java applications are caused by incorrect setting of environment variables ( global system variables available to all the processes/users running under the Operating System), in particular, PATH , CLASSPATH and JAVA_HOME .

When you launch a program from the command line, the Operating System uses the PATH environment variable to search for the program in your local file system. In other words, PATH maintains a list of directories for searching executable programs .

PATH (For Windows)

For example, if you are trying to use Java Compiler " javac.exe " to compile a Java source file, but " javac.exe " cannot be found in the current directory and all the directories in the PATH , you will receive the following error:

PATH maintains a list of directories. The directories are separated by semicolon ( ; ) in Windows.

For Java applications, PATH must include the following directories:

  • JDK's " bin " (binary) directory (e.g., " c:\Program Files\java\jdk1.x.x\bin "), which contains JDK programs such as Java Compiler " javac.exe " and Java Runtime " java.exe ".
  • " c:\windows\system32 " and " c:\windows " which contain console programs and commands.

The JDK's " bin " directory should be listed before " c:\windows\system32 " and " c:\windows " in the PATH . This is because some older Windows systems provide their own Java runtime (which is often outdated) in these directories (try search for " java.exe " in your computer, you may find a few entries).

To add a directory (say JDK's " bin ") to the existing PATH, check " How to add a directory to the PATH ".

PATH (For macOS/Linux)

For example, if you are trying to use Java Compiler " javac " to compile a Java source file, but " javac " can not be found in the list of directories in the PATH , you will receive the following error:

To support Java applications, you need to include the JDK's " bin " (binary) directory in the PATH. See " How to add a directory to the PATH ".

Java Archive (JAR) File

For ease of distribution, Java classes are often archived (zipped) together into a so-called JAR file. To use a third-party Java package, you need to place the distributed JAR file in a location that is available to the Java Compiler and Java Runtime.

How Classes are Found?

Java Compiler (" javac "), Java Runtime (" java ") and other Java tools searches for classes used in your program in this order:

  • Java platform (bootstrap) classes: include system classes in core packages ( java.* ) and extension packages ( javax.* ) in " rt.jar " (runtime class), " i18n.jar " (internationalization class), charsets.jar , jre/classes , and others.
  • For Windows, the Java Extension Directory is located at " <JAVA_HOME>\jre\lib\ext " (e.g., " c:\Program Files\Java\jdk1.7.0_{xx}\jre\lib\ext ").
  • For macOS, the JDK extension directories are " /Library/Java/Extensions " and " /System/Library/Java/Extensions ".
  • For Ubuntu, the JDK extension directories are " <JAVA_HOME>/jre/lib/ext " (e.g., " /usr/user/java/jdk1.7.0_{xx}/jre/lib/ext ") and " /usr/java/packages/lib/ext ".
  • Defaulted to the current working directory ( . ).
  • Entries in the CLASSPATH environment variable, which overrides the default.
  • Entries in the -cp (or -classpath ) command-line option, which overrides the CLASSPATH environment variable.
  • The runtime command-line option -jar , which override all the above.

Cannot Find Classes

If the Java Runtime (" java ") cannot find the classes used in your program in all the above places, it will issue error "Could not find or load main class xxxx" (JDK 1.7) or "java.lang.NoClassDefFoundError" (Prior to JDK 1.7).

Similarly, Java Compiler (" javac ") will issue compilation errors such as "cannot find symbol", "package does not exist".

Notes : External native libraries (" .lib ", " .dll ", " .a ", " .so ") are to be found in a path in JRE's Property " java.library.path ", which normally but not necessarily includes all the directories in the PATH environment variable. Otherwise, you will get a runtime error " java.lang.UnsatisfiedLinkError: no xxx in java.library.path ".

CLASSPATH Environment Variable

The CLASSPATH environment variable could include directories (containing many class files) and JAR files (a single-file archive of class files). If CLASSPATH is not set, it is defaulted to the current directory. If you set the CLASSPATH , it is important to include the current working directory ( . ). Otherwise, the current directory will not be searched.

A common problem in running hello-world program is: CLASSPATH is set but does not include the current working directory. The current directory is therefore not searched, which results in "Error: Could not find or load main class Hello". You can simply remove the CLASSPATH , and leave the class path defaulted to the current directory.

For a beginner, no explicit CLASSPATH setting is required. The default CLASSPATH setting of current directory is sufficient. Remove all CLASSPATH setting if there is any. However, if you have to set CLASSPATH , make sure that you include the current directory '.' .

The PATH environment variable (for searching the executable programs) is applicable to all applications; while CLASSPATH is used by Java only.

Read JDK documents "Setting the CLASSPATH " and "How Classes are Found" (you can find the hyperlinks from the index page of the JDK documentation, or googling).

CLASSPATH Environment Variable (For Windows)

The CLASSPATH accepts directories and jar-files. Path entries are separated by semicolon ( ; ).

Example: Displaying and changing CLASSPATH for the current CMD session.

You can set the CLASSPATH permanently. See " How to Set an Environment Variable ".

CLASSPATH (for macOS/Ubuntu)

  • To set the CLASSPATH for the current session, issue this command: export CLASSPATH=.:/usr/local/tomcat/bin/servlet-api.jar Use colon ' : ' as the path separator (instead of semicolon ' ; ' in Windows).
  • To set the CLASSPATH permanently, place the above export command in the bash shell initialization script ( .bashrc or .bash_profile of the home directory or /etc/profile for all users). See " How to Set an Envrionment Variable ".


Many Java applications (such as Tomcat) require the environment variable JAVA_HOME to be set to the JDK installed directory.

How to Set JAVA_HOME in Windows

First, check if JAVA_HOME is already set by start a CMD and issue:

If JAVA_HOME is not set, you will receive "Environment variable JAVA_HOME not defined". Otherwise, the current setting will be shown.

To set/change JAVA_HOME in Windows:

  • In "Variable Name", enter "JAVA_HOME".
  • In "Variable Value", click "Browse Directory..." and navigate to the JDK installed directory (e.g., " C:\Program Files\Java\jdk-15.0.xx ").
  • OK ⇒ OK ⇒ OK.
  • Select " JAVA_HOME " ⇒ "Edit"

To verify the new setting, re-start CMD:

How to Set JAVA_HOME in Linux/macOS (Bash Shell)

First, check if JAVA_HOME is already set by start a terminal and issue:

JAVA_HOME is to be set to the JDK installed directory. You need to find your JDK installed directory.

[TODO] find macOS and Ubuntu JDK installed directory.

Add the the following line at the end of "~/.bashrc " (or " ~/.login "). Take note that filename beginning with dot ( . ) is hidden by default.

[TODO] How to un-hide for macOS/Ubuntu.

You need to refresh the bash shell for the new settings to take effect. Issue a " source " command as follows:

Windows vs. Unixes/macOS

Java is platform independent. Java classes run in Windows as well as Unixes - binary compatible.

  • Unixes have many shells, such as the newer bash and the older csh , ksh . Windows have two shells: the newer cmd.exe and the older command.com . Each shell come with its own set of commands, utilities, and its own scripting programming language.
  • Unix's variable name is denoted as $ varname , e.g., $CLASSPATH . Windows uses % varname % , e,g., %CLASSPATH% .
  • Unix uses command " printenv " (print environment) or " env " to list all the environment variables. Windows uses command " set ".
  • Unix's PATH is set permanently in the login or shell initialization script (e.g., " ~/.login ", " ~/.profile ", " ~/.bashrc ", " ~/.bash_profile ", or " /etc/profile "). Windows' PATH is set permanently via Control Panel ⇒ System ⇒ ....
  • The current directory is NOT included in the Unix's PATH implicitly. To run a program in the current directory, you need to issue " ./programName " where " . " denotes the current directory. It is recommended to include the current directory ( . ) in the PATH explicitly. On the other hand, current directory is included in Windows' PATH implicitly.
  • A Windows' path includes a drive letter and directories. Each drive has a root directory. It uses back-slash '\' as directory separator (e.g., " c:\jdk1.6\bin "). Linux's paths do not have drive letter. There is a single root. Unix uses forward slash '/' as the directory separator (e.g., " /usr/bin/jdk1.6 ").
  • Windows use semicolon ';' as path separator (e.g., in PATH environment variable), while Unix uses colon ':' .
  • Windows/DOS uses " 0D0AH " (carriage-return plus line-feed) as line-break (or End-of-Line (EOL), or newline). Unixes/macOS uses " 0AH " (line-feed) only.

Last modified: March, 2020

Batch Script Tutorial

  • 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.

Command Line Arguments

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

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.

Setting and using variable within same command line in Windows cmd.exe

In Bash, I can do EDITOR=vim command and command will be run with EDITOR set to vim , but this won't affect the value of EDITOR in the shell itself. Is it possible to do this in cmd.exe ?

  • command-line

sactiw's user avatar

  • Would Powershell answers be acceptable here as well? ( superuser.com/q/1049430/185554 which did not limit itself to cmd.exe was closed as a duplicate of this) –  Gert van den Berg Apr 20, 2021 at 10:00
  • 2 @GertvandenBerg I certainly wouldn't object, but I don't know if moderators would (or if I should edit question title/body to extend it). –  Alexey Romanov Apr 20, 2021 at 11:03

5 Answers 5

Note that cmd /C "set "EDITOR=vim" && echo %EDITOR%" would not work. Nor would cmd /C "setlocal ENABLEDELAYEDEXPANSION && set "EDITOR=vim" && echo !EDITOR!"

You would need:

  • the /V option, to enable delayed environment variable expansion using ! as delimiter.
  • no space between a command and the && (or add quotes)

As noted below by maoizm , it is cmd /V /C , not cmd /C /V (which would not work)

I can't think of any practical reason you'd ever actually want this within the context of a single command

Typically, you need this when you have to replace a value used multiple times in a long command line. For instance, to deploy a file to Nexus (in multiple lines for readability):

Instead of having to replace group, artifact (used 2 times) and version in a long and complex command line, you can edit them at the beginning of said command. It is clearer/easier to manipulate and change the parameter values.

VonC's user avatar

  • 2 Tested it on my machine with Windows 10 version 1607, the cmd prompt crashes. –  Fernando Costa Bertoldi Dec 21, 2016 at 20:37
  • Note that EDITOR will not be set to 'vim' but 'vim ' in the last command. Add the internal quotes to avoid the space in the end. –  Zitrax Feb 3, 2017 at 11:57
  • 3 NB: interesting: the order of switches matters in this case. cmd /v/c "..." works, but cmd /c/v "..." fails -- hopefully it can save you 15 minutes –  maoizm Jun 4, 2017 at 11:12
  • 2 @DerekGreer " I can't think of any practical reason": OK, I have edited the answer to add a practical reason. –  VonC Jul 21, 2017 at 6:20
  • 4 @DerekGreer This is also useful (and commonly used in *Nix) for apps that read environment variables. (e.g. EDITOR=emacs git commit ) On windows, it could also be used to load DLLs from a custom location, by setting DEVPATH docs.microsoft.com/en-us/dotnet/framework/configure-apps/… –  iCodeSometime Jan 23, 2020 at 18:32

You can do it in windows like this no need for installing anything.

You'll see a list of variables and you'll see EDITOR=vim, now run "set" again and it won't be listed.

You can do multiple &&'s to add additional commands:

EDIT: /C exits the new cmd right away after running, if you produce output with the new one it will still be visible in the parent window.

You can opt to use /K in which case the new cmd window stays open at the end of the run.

Viper_Sb's user avatar

  • 11 Be careful. Setting the variable this way will result in a trailng space in the variable EDITOR: "vim ". To avoid the trailing space use: cmd /C "set "EDITOR=vim" && do this && do that" –  Gerd K Apr 3, 2015 at 12:00
  • 2 This is not working on "Windows Server 2008", for example. I tried this: set name="username" && echo %username%. And username is empty. –  akozin May 15, 2015 at 12:10
  • @akozin Do you realize that you got the keyvalue backwards? Did you mean set name=foo&&echo %name% or set username=foo&&echo %username% ? –  Phrogz Jul 30, 2015 at 23:00
  • @akozin see my answer below –  VonC Aug 5, 2015 at 6:03
  • Your cmd = OP's command ? –  Iulian Onofrei Oct 9, 2020 at 7:47

you can use ported util env from package CoreUtils in GnuWin32 http://gnuwin32.sourceforge.net/

  • Check what directory with env.exe exists in %PATH% variable
  • Use same way like linux version env EDITOR=vim command

Red Skotina's user avatar

  • 4 maybe worth saying that if you have git/docker/msys/cygwin you'll already have a version of this. –  xenoterracide Feb 26, 2018 at 16:29
  • This is specially a good choice for those who have Git Bash installed (almost every programmer these days). You can use the C:\Program Files\Git\usr\bin\env.exe executable. –  Marcelo Barros Jun 20, 2021 at 15:52

Vonc's answer will work for commands that reference the variable as expanded (that is !FOO! instead of %FOO% )

However, It won't work if your command references a regular variable.

For example consider:

some-bat.bat (or any other executable/batch process)

And the main process:

Returns foo instead of bar (a second execution would work though)

But still, you could concatenate a new cmd process to force the refresh of the variable.

Or in case the main command already had to use a new cmd:

Julio's user avatar

  • 2 Very good point. Upvoted. –  VonC Apr 29, 2021 at 10:05

I have knocked up a batch file env.cmd which works more or less like the Linux env command:-

The only difference is that, because of the way cmd parses, the environment assignments need to be quoted, so your command would be:

The batch file could be elaborated to remove the 8-parameter restriction by building up the command string within the for loop (delayed expansion will be needed).

AFH's user avatar

  • Why not just use %* as the penultimate line (i.e., the one after the :DoCmd label) to allow for very long user commands? –  Scott - Слава Україні May 22, 2016 at 23:47
  • 3 @Scott - Because %* is the original parameter list: it is unaffected by shift (unlike $* in Unix). –  AFH May 23, 2016 at 0:34

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged windows command-line shell ..

  • The Overflow Blog
  • How to scale a business-ready AI platform with watsonx: Q&A with IBM sponsored post
  • Will developers return to hostile offices?
  • Featured on Meta
  • We're rolling back the changes to the Acceptable Use Policy (AUP)
  • Seeking feedback on tags update

Hot Network Questions

  • Kohanim hand symbol
  • "You Search the Scriptures" - How has the democratization of access to the scriptures affected biblical hermeneutics? (John 5:33, 39)
  • PSE Advent Calendar 2023 (Day 2): Wall I want for Christmas
  • Sci fi book where humanoid aliens murder a researcher by killing him and cutting him open
  • Accumulated instance count of each list element
  • Is it possible in Mathematica to get a step-by-step evaluation of the following?
  • What would the effects of a space based laser weapon system capable of tracking and destroying any projectile posing a threat to human life?
  • the proof of <the> pudding is in the eating
  • US swap spreads
  • Can sine converge to zero at infinity?
  • Advent of code 2023 day 2 in pure Bash
  • Guitar Cabinet volume low
  • Do I need a junction box for thermostat wire splices?
  • Did Netanyahu say (apparently in 2001) "I actually stopped the Oslo Accords"?
  • Why are there so many pro-Palestinian protestors in the United States?
  • Is there a reason why the EU doesn't pursue a FTA with each individual ASEAN country instead of a region-region agreement?
  • High memory usage after copying 1 million small files (Win10 x64)
  • Probabilty measures that are both discrete and continuous
  • If I cut out a square of drywall for access, should I tape the seams when I put it back?
  • Can a creature controlled by Dominate Person warn his allies?
  • Do the qualities of a vowel determine its semivowel’s place of articulation?
  • Exponential operator approximation
  • Filter Airbnb rooms for Eiffel tower view
  • Yield of construction gingerbread

assign variable cmd

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 .

Command Windows


  • 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

Site navigation

  • Assoc and Ftype
  • Batch files- basics
  • Batch files - branching
  • Batch files- iterating
  • Command Line- Introduction
  • Command line list and reference
  • Commands that everybody can use
  • Configuring the command prompt window
  • Disk management-Diskpart
  • Net Services
  • Network Services Shell
  • Start-Run line
  • Support tools
  • Tips for using the command shell
  • Tskill and Taskkill
  • Variables and "Set"
  • Windows 7 command list

Related links

  • Computer Education
  • Blog with tips
  • Windows for Beginners

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


  • 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


  1. Assign Variable

    assign variable cmd

  2. How to Set the PATH Variable in Windows

    assign variable cmd

  3. Manage Variables

    assign variable cmd

  4. How To Assign IP Address Using CMD in WIndows 10

    assign variable cmd

  5. Assign variable

    assign variable cmd

  6. equation solving

    assign variable cmd


  1. CMD Expert🚨

  2. assign variable in c program #cprogramming #coding #cprogrammingvideo #tutorial

  3. Variable Assignment in Python #python #coder #coding #tutorial #programming #variables

  4. CODING ACADEMY for KIDS (8/11/2023)

  5. How to assign values to variable in python



  1. What Is a Qualitative Variable?

    Qualitative variables are those with no natural or logical order. While scientists often assign a number to each, these numbers are not meaningful in any way. Examples of qualitative variables include things such as color, shape or pattern.

  2. How Do I Fix C Windows System32 CMD EXE?

    According to Microsoft, there are two methods to fix a C:/Windows/system32/cmd.exe error: boot the computer into safe mode, then troubleshoot to determine the cause of the issue, or perform a system restore. C:/Windows/system32/cmd.exe erro...

  3. What Is the Meaning of Experimental Research?

    In experimental research, researchers use controllable variables to see if manipulation of these variables has an effect on the experiment’s outcome. Additionally, subjects of the experimental research are randomly assigned to prevent bias ...

  4. Set

    SETX - Set an environment variable permanently. Parameters - get a full or partial pathname from a command line variable. StackOverflow - Storing a Newline in a

  5. Defining and using a variable in batch file

    Batch File Set Variable not working · 13 · Why is no string output with 'echo %var%' after using 'set var = text' command in cmd? 2 · Setting

  6. Set (environment variable)

    Reference article for set, which displays, sets, or removes cmd.exe environment variables.

  7. Environment Variables in Windows/macOS/Linux

    To set (or change) a environment variable, use command " set varname=value ". There


    How to set variable values and use them by using the command SET in cmd. Syntax & examples: https://ss64.com/nt/set.html.

  9. Batch Script

    Syntax · 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

  10. How do I set an environment variable on the command line and

    Shells convert each of the variables they receive from their environment to a shell variable, so the var environment variable sh receives will

  11. Assigning directory name to a variable in cmd batch

    Assigning directory name to a variable in cmd batch ... I want to retrieve a file name and assign it to a variable so I can use it further in the

  12. Setting and using variable within same command line in Windows

    Note that cmd /C "set "EDITOR=vim" && echo %EDITOR%" would not work. Nor would cmd /C "setlocal ENABLEDELAYEDEXPANSION && set "EDITOR=vim"

  13. Set Environment Variable in Windows {How-To}

    Set Environment Variable in Windows via Command Prompt · [variable_name] : The name of the environment variable you want to set. · [variable_value]

  14. The Set command and how to use variables in the Windows

    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