Programming Field

‘%’ (Use environment variable) - DOS/Command Prompt Reference

‘%’ (percent character) is used to retrieve the value of environment variables and parameters of batch programs.

Syntax

%<value-name>%
%<number>
%*
%~<operators><number>
<value-name> Specifies the name of the environment variable defined in the current environment.
<number> (*)

[Batch file] Specifies the number 0 to 9. This number corresponds to the index of parameters passed to the batch program. (When Shift is not called, ‘%1’ refers to the first parameter, and ‘%0’ refers to the batch file name or the label name called with Call command.)

%* [Windows NT series] [Batch file] Used to retrieve the entire parameter passed to the batch program (not including ‘%0’). Even if the parameters are splitted with two or more spaces, ‘%*’ is expanded as-is (i.e. including two or more spaces). This variable is not affected by the Shift command.
%~<operators><number> (*) [Windows NT series] [Extensions] [Batch file] Using ‘~’ and valid characters just before 0 to 9 numbers will change the expansion of parameters. For details please see ‘Enhanced parameter substitution’.

The syntaxes (*) will also be applied to the variables used in For command. (Note that in batch files two consecutive ‘%’ characters such as ‘%%A’ or ‘%%~dpX’ must be used for For command variables.)

Details

An environment variable is a kind of settings for the current environment (including the prompt session) and some programs depend on the values of environment variables. (For details please see ‘Using environment variables’.) By using ‘%’ character, you can use the value of the environment variable.

To see the list of environment variables defined in the current session, or to add/change/remove the environment variable, use Set command.

Interpretation of % character

If the string surrounded by % appears in the command line or the batch file, the system (the command interpreter) treats the string as the name of an environment variable, and substitutes it with the value of the variable. If the variable is not defined, the system substitutes with an empty string.

(Sample for displaying the values of environment variables:)

echo ‘%TEMP%’ ‘%UNKNOWN_VARIABLE%’
‘C:\TEMP’ ‘’

Note that in batch files you must write ‘%%’ to print ‘%’ character or pass as a part of a parameter to a program.

* You cannot print ‘%’ character even if you use ‘^’ character (i.e. writing ‘^%’).
* This is the reason that you must write ‘%%’ instead of ‘%’ in For command in batch files.

(Sample for printing ‘%’ character: batch file ‘C:\MyData\test.bat’)

@echo 100%% 100%
C:\MyData>test.bat
100% 100

The command interpreter (cmd.exe) always interprets % character first on interpreting the command line. When the multiple commands written with ‘&’ character or ‘( )’ characters are to be executed, all ‘%’ characters are interpreted before all execution of the commands. In particular, it may cause unexpected behavior that the commands include Set command or etc., so it is necessary to take measures such as enabling delayed environment variable expansion (by using Setlocal command) and expanding environment variables by using ‘!’ characters.

Parameters of batch programs

For executing batch files, you can specify parameters to the batch files just like any other programs. If you want to use the specified parameters in the batch file, you can use % characters and numbers such as ‘%1’, ‘%2’, etc. to retrieve values. Note that ‘%0’ contains the path of executing batch file (or the label name including ‘:’ for Call calls).

(Sample for using parameters: batch file ‘C:\test2.bat’)

@echo "%0", "%1", "%2", "%3"
C:\MyData>..\test2.bat Test "parameter"
"..\test2.bat", "Test", ""parameter"", ""

* You can only use one digit after % character. To use 10 or more parameters, use Shift command.

Enhanced environment variable substitution

[Windows NT series] [Extensions] If Command Extensions are enabled, you can change the substitution of environment variables by using following syntax.

SyntaxMeanings
%VAR%(normal syntax)
%VAR:text1=text2%Expands with replacing alltext1’ strings included by VAR with the string ‘text2’.
%VAR:~num1,num2%Expands with picking up the substring of num2 characters of VAR from the offset num1 ((num1+1)th character). If VAR contains ‘Hello’, ‘%VAR:~1,2%’ will be expanded to ‘el’.
If num1 is negative, picks up the substring of num2 characters of VAR from the offset -num1 ((-num1)th character) counted from the end. If VAR contains ‘Hello’, ‘%VAR:~-2,2%’ will be expanded to ‘lo’.
If num2 is negative, picks up the substring excluding last -num2 characters of VAR from the offset num1 ((num1+1)th character). If VAR contains ‘Hello’, ‘%VAR:~1,-1%’ will be expanded to ‘ell’.
%VAR:~num1%Expands with picking up the substring of VAR from the offset num1 ((num1+1)th character) to the last. If VAR contains ‘Hello’, ‘%VAR:~2%’ will be expanded to ‘llo’.
If num1 is negative, picks up the substring of VAR from the offset -num1 ((-num1)th character), counted from the end, to the last. If VAR contains ‘Hello’, ‘%VAR:~-1%’ will be expanded to ‘o’.

Even if the position is out of range, it will not be an error, and the out-of-range part will become an empty string. (If the whole is out of range, an empty string will be expanded to.) If VAR contains ‘Hello’, ‘%VAR:~7%’ will be expanded to ‘’.

Enhanced parameter substitution

[Windows NT series] [Extensions] When expanding parameters of batch programs (%0 to %9), inserting ‘~’ character just after ‘%’ will change the substitution of parameters. By specifying following characters between ‘~’ and the digit 0 to 9, the substitution will be as follows.

  • In the followings, ‘1’ can be replaced with 0 to 9, ‘ENV’ refers to existing environment variable name (‘PATH’ or etc.).
  • In ‘Sample of substitution’, the original value of ‘%1’ is ‘"Text Documents\note.201311.txt"’, and the current directory is ‘D:\MyDocs’.
  • You can also use the following syntaxes for variables in For command, but you cannot for environment variables. To use following extensions for normal environment variables, you need to use the method like the sample of Call page or to use text parsing with For command (/F option).
SyntaxMeanings / Sample of substitution
%1(No extension)
"Text Documents\note.201311.txt"
%~1(In case no chracters between ‘~’ and the digit) Expands with removing double quotation marks ‘"’ in the parameter. Only the first and last character are removed. Note that the following syntaxes will also removes double quotation marks.
Text Documents\note.201311.txt
%~f1Treats the value of the parameter as the relative path file name, and expands to the absolute path file name converted from the relative path. In this case the file does not need to exist.
D:\MyDocs\Text Documents\note.201311.txt
%~d1Extracts the drive letter and ‘:’ from the parameter. If the parameter contains the relative path, this syntax will be applied to the absolute path converted from the parameter's relative path.
D:
%~p1Extracts the directory name only from the parameter. The directory name does not contain the drive letter and ‘:’, and it always contains ‘\’ symbol in the last. If the parameter contains the relative path, this syntax will be applied to the absolute path converted from the parameter's relative path.
\MyDocs\Text Documents\
%~dp1(The combination of ‘%~d1’ and ‘%~p1’. Used to extract the absolute directory path (not including the file name). The path always contains ‘\’ in the last.)
D:\MyDocs\Text Documents\
%~n1Extracts the file name without the file extension (and the directory path) from the parameter. This syntax only removes the last ‘.’ and following characters, so the expanded string may contain ‘.’ character like ‘file.exe.config’ → ‘file.exe’.
note.201311
%~x1Extracts the file extension from the parameter. If no extension is included, expands to an empty string.
.txt
%~nx1(The combination of ‘%~n1’ and ‘%~x1’. Used to extract the file name only.)
note.201311.txt
%~s1Treats the value of the parameter as the relative path file name, converts it to the absolute path, and then converts it to the ‘short file name (path)’ before expanding. If the file does not exist, only the part of existing directory will be converted to the short name.
You can combine with n, d, and etc. (see below)
D:\MyDocs\TEXTDO~1\NOTE-2~1.txt
%~snx1(When combining s with n, d, and etc., expands corresponding part of the short file name. In this case the short name version of ‘%~nx1’ will be expanded.)
NOTE-2~1.txt
%~a1
Treats the value of the parameter as the relative path file name, and expands to the file attribute string. The attribute string format is ‘drahscotl’ or ‘drahscotlvx’ ([Windows 8.1? or later]), and each characters have the following meanings:
  • d=directory
  • r=read-only
  • a=archive
  • h=hidden file
  • s=system file
  • c=compressed file
  • o=offline file
  • t=temporary file
  • l=symbolic link, junction, or reparse point
  • v=integrity stream ([Windows 8.1? or later])
  • x=no scrub file ([Windows 8.1? or later])
If the file does not have some of those attributes, the character of corresponding part will be ‘-’. In case the file does not exist, an empty string will be expanded.
* Integrity stream ‘v’ is an attribute used in ReFS file system.
--a------
--a-------- [Windows 8.1? or later]
%~t1Treats the value of the parameter as the relative path file name, and expands to the values of the file date and time. If the file does not exist, an empty string will be expanded.
2013/11/30 17:25
%~z1Treats the value of the parameter as the relative path file name, and expands to the values of the file size. The file size is in bytes without digit separator. If the file does not exist, an empty string will be expanded.
34122
%~$ENV:1Treats the value of the parameter as the file name, searches the file from the directory list specified in the environment variable ENV, and expands to the absolute path of combination of the first directory, where the parameter's file is found, and the parameter's file name. The value of ENV must be semicolon-separated directory list like the environment variable PATH. For example, when the parameter %1 has the value ‘hoge.exe’ and ENV contains ‘C:\foo;C:\bar;C:\piyo’ and ‘hoge.exe’ is found in ‘C:\bar’, ‘%~$ENV:1’ will be expanded to ‘C:\bar\hoge.exe’.
If the parameter's file name is a relative path without dot-only paths (. or ..), the file is searched as the relative path from each directory in the directory list. When the parameter is an absolute path, the expanded value will be as-is if the file exists, or empty if the file does not exist.
E:\Backup\2013\Text Documents\note.201311.txt (* suppose ENV includes ‘E:\Backup\2013’)

These syntaxes can be combined; ‘%~dp1’ will be expanded to the drive letter and the directory of the parameter's absolute path, and ‘%~dp$PATH:1’ will be expanded to the name (including the drive letter) of the first directory where the %1 file is found in ‘PATH’.

* When combining, the order of expanded value is always the same regardless of the order of letters, and the order of values is ‘attribute date-time size file-path’. And, if ‘f’ is included, ‘d’, ‘p’, ‘n’, and ‘x’ will be ignored.
* Only ‘$ENV:’ must be in the last. You cannot combine other letters after ‘:’ character. (You cannot specify as ‘%~$PATH:f1’.)

Dynamic environment variables

[Windows NT series] [Extensions] If Command Extensions are enabled, the following dynamic environment variables can be used. Note that these are just dynamic environment variables, so Set does not list these variables, and when assigning a value to these variables using Set, what the variable refer to does not change and a new variable with the same name will be created.

NameValue
%CD%The current directory (same as the output of Cd command).
%DATE%The current date (almost same as the output of Date command).
%TIME%The current time. Includes 1/100th of a second which is slightly different from the output of Time command.
%RANDOM%The random integer value between 0 and 32767. The value changes every time you use.
%ERRORLEVEL%The exit code from the last executed command/program (including the batch program). (see also If Errorlevel)
%CMDEXTVERSION%The Command Extensions version.
%CMDCMDLINE%The original command line showing how the current running Command Prompt was executed.
%HIGHESTNUMANODENUMBER%The highest NUMA node number on this machine.

Samples

Sample 1

C:\>%SystemRoot%\system32\notepad.exe

[Windows NT series] Runs notepad.exe located in the Windows system directory.

Sample 2 (Batch file)

@echo off
set TEMP_VAL=
foo.exe /all
if errorlevel 255 set TEMP_VAL=ERROR
if errorlevel 1 set TEMP_VAL=FAILED
bar.exe /refresh
if "%TEMP_VAL%"=="ERROR" goto OnError
if "%TEMP_VAL%"=="FAILED" goto OnFailed
echo Succeeded.
goto OnFinish

:OnError
echo An error has occurred.
goto OnFinish

:OnFailed
echo Some files have wrong data.

:OnFinish
set TEMP_VAL=

Creates the environment variable ‘TEMP_VAL’ in the batch file to store the result of ‘foo.exe /all’. After executing ‘bar.exe /refresh’, the program checks the value of TEMP_VAL and does conditional branching. Lastly, removes the variable TEMP_VAL from the environment.

Sample 3 (Batch file)

@echo off
setlocal
set PATH2=.;%PATH%
set TEMP_VAL=%~$PATH2:1
if not "%TEMP_VAL%"=="" goto ok

echo %~nx0: no %~1 in (%PATH2%)>&2
exit /b 1

:ok
echo %TEMP_VAL%

exit /b 0

[Windows NT series] [Extensions] This is a batch program sample which behavior is similar to ‘which’ command in Linux. If you pass a file name (without directory paths) to this batch program, the program searches the file from the current directory and the environment variable PATH, and outputs the found file name to the standard output (STDOUT), or outputs ‘no xxx in ...’ to the standard error (STDERR) if not found. This program uses output redirection ‘>’ to output to the standard error.

See also