Recent from talks
Nothing was collected or created yet.
Environment variable
View on WikipediaThis article needs additional citations for verification. (May 2023) |
An environment variable is a user-definable value that can affect the way running processes will behave on a computer. Environment variables are part of the environment in which a process runs. For example, a running process can query the value of the TEMP environment variable to discover a suitable location to store temporary files, or the HOME or USERPROFILE variable to find the directory structure owned by the user running the process.
They were introduced in their modern form in 1979 with Version 7 Unix, so are included in all Unix operating system flavors and variants from that point onward including Linux and macOS. From PC DOS 2.0 in 1982, all succeeding Microsoft operating systems, including Microsoft Windows, and OS/2 also have included them as a feature, although with somewhat different syntax, usage and standard variable names.
Design
[edit]In all Unix and Unix-like systems, as well as on Windows, each process has its own separate set of environment variables. By default, when a process is created, it inherits a duplicate run-time environment of its parent process, except for explicit changes made by the parent when it creates the child. At the API level, these changes must be done between running fork and exec. Alternatively, from command shells such as bash, a user can change environment variables for a particular command invocation by indirectly invoking it via env or using the ENVIRONMENT_VARIABLE=VALUE <command> notation. A running program can access the values of environment variables for configuration purposes.
Shell scripts and batch files use environment variables to communicate data and preferences to child processes. They can also be used to store temporary values for reference later in a shell script. However, in Unix, non-exported variables are preferred for this as they do not leak outside the process.
In Unix, an environment variable that is changed in a script or compiled program will only affect that process and possibly child processes. The parent process and any unrelated processes will not be affected. Similarly, changing or removing a variable's value inside a DOS or Windows batch file will change the variable for the duration of COMMAND.COMor CMD.EXE's existence, respectively.
In Unix, the environment variables are normally initialized during system startup by the system init startup scripts, and hence inherited by all other processes in the system. Users can, and often do, augment them in the profile script for the command shell they are using. In Microsoft Windows, each environment variable's default value is stored in the Windows Registry or set in the AUTOEXEC.BAT file.
On Unix, a setuid program is given an environment chosen by its caller, but it runs with different authority from its caller. The dynamic linker will usually load code from locations specified by the environment variables $LD_LIBRARY_PATH and $LD_PRELOAD and run it with the process's authority. If a setuid program did this, it would be insecure, because its caller could get it to run arbitrary code and hence misuse its authority. For this reason, libc unsets these environment variables at startup in a setuid process. setuid programs usually unset unknown environment variables and check others or set them to reasonable values.
In general, the collection of environment variables function as an associative array where both the keys and values are strings. The interpretation of characters in either string differs among systems. When data structures such as lists need to be represented, it is common to use a colon (common on Unix and Unix-like) or semicolon-delineated (common on Windows and DOS) list.
Syntax
[edit]The variables can be used both in scripts and on the command line. They are usually referenced by putting special symbols in front of or around the variable name.
By convention, names of environment variables are normally expressed in all capital letters. This helps keep environment variables distinctly different from other variables and identifiers used in programming codes. Nevertheless, note that case sensitivity in environment variable names differs between operating systems. That is, Unix-like operating systems are case-sensitive with respect to environment variable names, while DOS, OS/2, and Windows are not case-sensitive.
Unix
[edit]In most Unix and Unix-like command-line shells, an environment variable's value is retrieved by placing a $ sign before the variable's name. If necessary, the name can also be surrounded by braces.
To display the user home directory, the user may type:
echo $HOME
In Unix and Unix-like systems, the names of environment variables are case-sensitive.
The command env displays all environment variables and their values. The command printenv can also be used to print a single variable by giving that variable name as the sole argument to the command.
DOS, OS/2 and Windows
[edit]In DOS, OS/2 and Windows command-line interpreters such as COMMAND.COM and CMD.EXE, an environment variable is retrieved by placing a % sign before and after it.
In DOS, OS/2 and Windows command-line interpreters as well as their API, upper or lower case is not distinguished for environment variable names.
The environment variable named HOMEDRIVE contains the drive letter (plus its trailing : colon) of the user's home directory, whilst HOMEPATH contains the full path of the user's home directory within that drive.
So to see the home drive and path, the user may type this:
ECHO %HOMEDRIVE%%HOMEPATH%
The command SET (with no arguments) displays all environment variables and their values. In Windows NT and later set can also be used to print all variables whose name begins with a given prefix by giving the prefix as the sole argument to the command.
In Windows PowerShell, the user may type any of the following:
echo $env:homedrive$env:homepath
Write-Output $env:homedrive$env:homepath
"$env:homedrive$env:homepath"
In PowerShell, upper or lower case is not distinguished for environment variable names.
The following command displays all environment variables and their values:
Get-ChildItem env:
Assignment: Unix
[edit]The commands env and set can be used to set environment variables and are often incorporated directly into the shell.
The following commands can also be used, but are often dependent on a certain shell.
VARIABLE=value # (there must be no spaces around the equals sign) export VARIABLE # for Bourne and related shells
export VARIABLE=value # for ksh, bash, and related shells
setenv VARIABLE value # for csh and related shells
A few simple principles govern how environment variables achieve their effect.
Environment variables are local to the process in which they were set. If two shell processes are spawned and the value of an environment variable is changed in one, that change will not be seen by the other.
When a child process is created, it inherits all the environment variables and their values from the parent process. Usually, when a program calls another program, it first creates a child process by forking, then the child adjusts the environment as needed and lastly the child replaces itself with the program to be called. This procedure gives the calling program control over the environment of the called program.
In Unix shells, variables may be assigned without the export keyword. Variables defined in this way are displayed by the set command, but are not true environment variables, as they are stored only by the shell and are unknown to all other processes. The printenv command will not display them, and child processes do not inherit them.
VARIABLE=value
The prefix syntax exports a "true" environment variable to a child process without affecting the current process:[1]
VARIABLE=value program_name [arguments]
The persistence of an environment variable can be session-wide or system-wide.
unset is a builtin command implemented by both the Bourne shell family (sh, ksh, bash, etc.) and the C shell family (csh, tcsh, etc.) of Unix command line shells. It unsets a shell variable, removing it from memory and the shell's exported environment. It is implemented as a shell builtin, because it directly manipulates the internals of the shell.[2][3] Read-only shell variables cannot be unset. If one tries to unset a read-only variable, the unset command will print an error message and return a non-zero exit code.
Assignment: DOS, OS/2 and Windows
[edit]In DOS, OS/2 and Windows command-line interpreters such as COMMAND.COM and CMD.EXE, the SET command is used to assign environment variables and values using the following arguments:
SET VARIABLE=value
An environment variable is removed via:
SET VARIABLE=
The SET command without any arguments displays all environment variables along with their values; SET " ", zero or more spaces, will include internal variables too. In CMD.EXE, it is possible to assign local variables that will not be global using the SETLOCAL command and ENDLOCAL to restore the environment.
Use the switch /? to display the internal documentation, or use the viewer help:
SET /?
HELP SET
SETLOCAL /?
HELP SETLOCAL
In PowerShell, the assignment follows a syntax similar to Unix:
$env:VARIABLE = "VALUE"
Examples
[edit]Examples of environment variables include:
PATH: a list of directory paths. When the user types a command without providing the full path, this list is checked to see whether it contains a path that leads to the command.HOME(Unix-like) andUSERPROFILE(Microsoft Windows): indicate where a user's home directory is located in the file system.HOME/{.AppName}(Unix-like) andAPPDATA\{DeveloperName\AppName}(Microsoft Windows): for storing application settings. Many applications incorrectly useUSERPROFILEfor application settings in Windows:USERPROFILEshould only be used in dialogs that allow user to choose between paths likeDocuments/Pictures/Downloads/Music; for programmatic purposes,APPDATA(for roaming application settings shared across multiple devices),LOCALAPPDATA(for local application settings) orPROGRAMDATA(for application settings shared between multiple OS users) should be used.[4]TERM(Unix-like): specifies the type of computer terminal or terminal emulator being used (e.g.,vt100ordumb).PS1(Unix-like): specifies how the prompt is displayed in the Bourne shell and variants.MAIL(Unix-like): used to indicate where a user's mail is to be found.TEMP: location where processes can store temporary files.
True environment variables
[edit]Unix
[edit]
$PATH- Contains a colon-separated list of directories that the shell searches for commands that do not contain a slash in their name (commands with slashes are interpreted as file names to execute, and the shell attempts to execute the files directly). It is equivalent to the DOS, OS/2 and Windows
%PATH%variable.
$HOME- Contains the location of the user's home directory. Although the current user's home directory can also be found out through the C-functions
getpwuidandgetuid,$HOMEis often used for convenience in various shell scripts (and other contexts). Using the environment variable also gives the user the possibility to point to another directory.
$PWD- This variable points to the current directory. Equivalent to the output of the command pwd when called without arguments.
$DISPLAY- Contains the identifier for the display that X11 programs should use by default.
$LD_LIBRARY_PATH- On many Unix systems with a dynamic linker, contains a colon-separated list of directories that the dynamic linker should search for shared objects when building a process image after
exec, before searching in any other directories.
$LIBPATHor$SHLIB_PATH- Alternatives to
$LD_LIBRARY_PATHtypically used on older Unix versions.
$LANG, $LC_ALL, $LC_...$LANGis used to set to the default locale. For example, if the locale values arept_BR, then the language is set to (Brazilian) Portuguese and Brazilian practice is used where relevant. Different aspects of localization are controlled by individual$LC_-variables ($LC_CTYPE,$LC_COLLATE,$LC_DATEetc.).$LC_ALLcan be used to force the same locale for all aspects.
$TZ- Refers to time zone. It can be in several formats, either specifying the time zone itself or referencing a file (in
/usr/share/zoneinfo).
$BROWSER- Contains a colon-separated list of a user's web browser preferences, for use by programs that need to allow the user to view content at a URL. The browsers in the list are intended to be attempted from first to last, stopping after the first one that succeeds. This arrangement allows for fallback behavior in different environments, e.g., in an X11 environment, a graphical browser (such as Firefox) can be used, but in a console environment a terminal-base browser (such as Lynx) can be used. A
%stoken may be present to specify where the URL should be placed; otherwise the browser should be launched with the URL as the first argument.[5][6][7][8][9]
DOS
[edit]
Under DOS, the master environment is provided by the primary command processor, which inherits the pre-environment defined in CONFIG.SYS when first loaded. Its size can be configured through the COMMAND /E:n parameter between 160[10] and 32767[10] bytes. Local environment segments inherited to child processes are typically reduced down to the size of the contents they hold. Some command-line processors (like 4DOS) allow to define a minimum amount of free environment space that will be available when launching secondary shells.[10] While the content of environment variables remains unchanged upon storage, their names (without the "%") are always converted to uppercase, with the exception of pre-environment variables defined via the CONFIG.SYS directive SET under DR DOS 6.0 and higher[11][12] (and only with SWITCHES=/L (for "allow lowercase names") under DR-DOS 7.02 and higher).[10][13] In principle, MS-DOS 7.0 and higher also supports lowercase variable names (%windir%), but provides no means for the user to define them. Environment variable names containing lowercase letters are stored in the environment just like normal environment variables, but remain invisible to most DOS software, since they are written to expect uppercase variables only.[10][11][12] Some command processors limit the maximum length of a variable name to 80 characters.[10] While principally only limited by the size of the environment segment, some DOS and 16-bit Windows programs[10][nb 1] do not expect the contents of environment variables to exceed 128 characters. DR-DOS COMMAND.COM supports environment variables up to 255, 4DOS even up to 512 characters.[10] Since COMMAND.COM can be configured (via /L:128..1024) to support command lines up to 1024 characters internally under MS-DOS 7.0 and higher, environment variables should be expected to contain at least 1024 characters as well. In some versions of DR-DOS, the environment passed to drivers, which often do not need their environment after installation, can be shrunken or relocated through SETENV or INSTALL[HIGH]/LOADHIGH options /Z (zero environment), /D[:loaddrive] (substitute drive, e.g. B:TSR.COM) and /E (relocate environment above program) in order to minimize the driver's effectively resulting resident memory footprint.[14][13][11][15][16][17]
In batch mode, non-existent environment variables are replaced by a zero-length string.
Standard environment variables or reserved environment variables include:
%APPEND%(supported since DOS 3.3)- This variable contains a semicolon-delimited list of directories in which to search for files. It is usually changed via the
APPEND /Ecommand, which also ensures that the directory names are converted into uppercase. Some DOS software actually expects the names to be stored in uppercase and the length of the list not to exceed 121[10] characters, therefore the variable is best not modified via theSETcommand. Long filenames containing spaces or other special characters must not be quoted (").
%CONFIG%(supported since MS-DOS 6.0 and PC DOS 6.1, also supported by ROM-DOS[18])- This variable holds the symbolic name of the currently chosen boot configuration. It is set by the DOS BIOS (
IO.SYS,IBMBIO.COM, etc.) to the name defined by the correspondingCONFIG.SYSdirectiveMENUITEMbefore launching the primary command processor. Its main purpose is to allow further special cases inAUTOEXEC.BATand similar batchjobs depending on the selected option at boot time. This can be emulated under DR-DOS by utilizing theCONFIG.SYSdirectiveSETlikeSET CONFIG=1.
%CMDLINE%(introduced with 4DOS, also supported since MS-DOS 7.0)- This variable contains the fully expanded text of the currently executing command line. It can be read by applications to detect the usage of and retrieve long command lines, since the traditional method to retrieve the command line arguments through the PSP (or related API functions) is limited to 126 characters and is no longer available when FCBs get expanded or the default DTA is used. While 4DOS supports longer command lines,
COMMAND.COMstill only supports a maximum of 126 characters at the prompt by default (unless overridden with/U:128..255to specify the size of the command line buffer), but nevertheless internal command lines can become longer through f.e. variable expansion (depending on/L:128..1024to specify the size of the internal buffer). In addition to the command-line length byte in the PSP, the PSP command line is normally limited by ASCII-13, and command lines longer than 126 characters will typically be truncated by having an ASCII-13 inserted at position 127,[12] but this cannot be relied upon in all scenarios.[12][nb 2] The variable will be suppressed for external commands invoked with a preceding@-symbol like in@XCOPY ...for backward compatibility and in order to minimize the size of the environment when loading non-relocating terminate-and-stay-resident programs. Some beta versions of Windows Chicago used%CMDLINE%to store only the remainder of the command line excessing 126 characters instead of the complete command line.[11][12]
%COMSPEC%(supported since DOS 2.0)- This variable contains the full 8.3 path to the command processor, typically
C:\COMMAND.COMorC:\DOS\COMMAND.COM. It must not contain long filenames, but under DR-DOS it may contain file and directory passwords. It is set up by the primary command processor to point to itself (typically reflecting the settings of theCONFIG.SYSdirectiveSHELL), so that the resident portion of the command processor can reload its transient portion from disk after the execution of larger programs. The value can be changed at runtime to reflect changes in the configuration, which would require the command processor to reload itself from other locations. The variable is also used when launching secondary shells.
%COPYCMD%(supported since MS-DOS 6.2 and PC DOS 6.3, also supported by ROM-DOS[18])- Allows a user to specify the
/Yswitch (to assume "Yes" on queries) as the default for theCOPY,XCOPY, andMOVEcommands. A default of/Ycan be overridden by supplying the/-Yswitch on the command line. The/Yswitch instructs the command to replace existing files without prompting for confirmation.
%DIRCMD%(supported since MS-DOS 5.0 and PC DOS 5.0, also supported by ROM-DOS[18])- Allows a user to specify customized default parameters for the
DIRcommand, including file specifications. Preset default switches can be overridden by providing the negative switch on the command line. For example, if%DIRCMD%contains the/Wswitch, then it can be overridden by usingDIR /-Wat the command line. This is similar to the environment variable%$DIR%under DOS Plus[19] and a facility to define default switches forDIRthrough its/Cor/Rswitches under DR-DOSCOMMAND.COM.[11]%DIRCMD%is also supported by the externalSDIR.COM/DIR.COMStacker commands under Novell DOS 7 and higher.[11]
%LANG%(supported since MS-DOS 7.0)- This variable is supported by some tools to switch the locale for messages in multilingual issues.
%LANGSPEC%(supported since MS-DOS 7.0)- This variable is supported by some tools to switch the locale for messages in multilingual issues.
%NO_SEP%(supported since PC DOS 6.3 and DR-DOS 7.07)- This variable controls the display of thousands-separators in messages of various commands. Issued by default, they can be suppressed by specifying
SET NO_SEP=ONorSET NO_SEP=1under PC DOS. DR-DOS additionally allows to override the system's thousands-separator displayed as in f.e.SET NO_SEP=..[10]
%PATH%(supported since DOS 2.0)- This variable contains a semicolon-delimited list of directories in which the command interpreter will search for executable files. Equivalent to the Unix
$PATHvariable (but some DOS and Windows applications also use the list to search for data files similar to$LD_LIBRARY_PATHon Unix-like systems). It is usually changed via thePATH(orPATH /Eunder MS-DOS 6.0) command, which also ensures that the directory names are converted into uppercase. Some DOS software actually expects the names to be stored in uppercase and the length of the list not to exceed 123[10] characters,[nb 1] therefore the variable should better not be modified via theSETcommand.[10] Long filenames containing spaces or other special characters must not be quoted ("). By default, the current directory is searched first, but some command-line processors like 4DOS allow "." (for "current directory") to be included in the list as well in order to override this search order; some DOS programs are incompatible with this extension.[10]
%PROMPT%(supported since DOS 2.0)- This variable contains a
$-tokenized string defining the display of the prompt. It is usually changed via thePROMPTcommand.
%TEMP%(and%TMP%)- These variables contain the path to the directory where temporary files should be stored. Operating system tools typically only use
%TEMP%, whereas third-party programs also use%TMP%. Typically%TEMP%takes precedence over%TMP%.
The DR-DOS family supports a number of additional standard environment variables including:
%BETA%- This variable contains an optional message displayed by some versions (including DR DOS 3.41) of
COMMAND.COMat the startup of secondary shells.[20]
%DRDOSCFG%/%NWDOSCFG%/%OPENDOSCFG%- This variable contains the directory[21] (without trailing "
\") where to search for.INIand.CFGconfiguration files (that is, DR-DOS application specific files likeTASKMGR.INI,TASKMAX.INI,VIEWMAX.INI,FASTBACK.CFGetc., class specific files likeCOLORS.INI, or global files likeDRDOS.INI,NWDOS.INI,OPENDOS.INI, orDOS.INI), as used by theINSTALLandSETUPcommands and various DR-DOS programs likeDISKOPT,DOSBOOK,EDIT,FBX,FILELINK,LOCK,SECURITY.OVL/NWLOGIN.EXE,SERNO,TASKMAX,TASKMGR,VIEWMAX, orUNDELETE.[11] It must not contain long filenames.
%DRCOMSPEC%- This variable optionally holds an alternative path to the command processor taking precedence over the path defined in the
%COMSPEC%variable, optionally including file and directory passwords. Alternatively, it can hold a special value of "ON" or "1" in order to enforce the usage of the%COMSPEC%variable even in scenarios where the%COMSPEC%variable may point to the wrong command-line processor, for example, when running some versions of the DR-DOSSYScommand under a foreign operating system.[22]
%DRSYS%- Setting this variable to "
ON" or "1" will force some versions of the DR-DOSSYScommand to work under foreign operating systems instead of displaying a warning.[22]
%FBP_USER%- Specifies the user name used by the FastBack command
FBXand{user}.FBconfiguration files under Novell DOS 7.[11]
%HOMEDIR%- This variable may contain the home directory under DR-DOS (including DR DOS 5.0 and 6.0).[11][20]
%INFO%- In some versions of DR-DOS
COMMAND.COMthis variable defines the string displayed by the$Itoken of thePROMPTcommand.[20] It can be used, for example, to inform the user how to exit secondary shells.
%LOGINNAME%- In some versions of DR-DOS
COMMAND.COMthis variable defines the user name displayed by the$Utoken of thePROMPTcommand, as set up by f.e. login scripts for Novell NetWare.[10][11][20] See also the similarly named pseudo-variable%LOGIN_NAME%.
%MDOS_EXEC%- This variable can take the values "
ON" or "OFF" under Multiuser DOS. If enabled, the operating system permits applications to shell out to secondary shells with the DOS Program Area (DPA) freed in order to have maximum DOS memory available for secondary applications instead of running them in the same domain as under DOS.[23][24]
%NOCHAR%- This variable can be used to define the character displayed by some commands in messages for "No" in
[Y,N]queries, thereby overriding the current system default (typically "N" in English versions of DR-DOS). If it contains a string, only the first character, uppercased, will be taken. Some commands also support a command line parameter/Yto automatically assume "Yes" on queries, thereby suppressing such prompts. If, however, the parameter/Y:ynis used to specify the "Yes"/"No" characters (thereby overriding any%NOCHAR%setting), queries are not suppressed. See also the relatedCONFIG.SYSdirectiveNOCHARand the environment variable%YESCHAR%.[22]
%NOSOUND%- Setting this variable to "
ON" or "1" will disable default beeps issued by some DR-DOS commands in certain situations such as to inform the user of the completion of some operation, that user interaction is required, or when a wrong key was pressed. Command line options to specifically enable certain beeps will override this setting.
%OS%- This variable contains the name of the operating system in order to distinguish between different DOS-related operating systems of Digital Research-origin in batch jobs and applications.[21] Known values include "
DOSPLUS" (DOS Plus 1.2 in DOS emulation), "CPCDOS 4.1" (DOS Plus 1.2 in CP/M emulation), "DRDOS" (DR DOS 3.31-6.0, DR DOS Panther, DR DOS StarTrek, DR-DOS 7.02[21]-7.05), "EZDOS" (EZ-DOS 3.41), "PALMDOS" and "NetWare PalmDOS" (PalmDOS 1.0), "NWDOS" (Novell DOS 7), "NWDOS7" (Novell DOS 7 Beta), "OPENDOS" (Caldera OpenDOS 7.01, Caldera DR-OpenDOS 7.02), "CDOS" (Concurrent DOS, Concurrent DOS XM), "CPCDOS" (Concurrent PC DOS), "CDOS386" (Concurrent DOS 386), "DRMDOS" (DR Multiuser DOS), "MDOS" (CCI Multiuser DOS),[23] "IMSMDOS" (IMS Multiuser DOS), "REAL32" (REAL/32).[11][25] MS-DOSINTERSVRlooks for a value of "DRDOS" as well.[25] See also the identically named environment variable%OS%later introduced in the Windows NT family.
%PEXEC%- In some versions of DR-DOS this variable defines the command executed by the
$Xtoken of thePROMPTcommand beforeCOMMAND.COMdisplays the prompt after returning from external program execution.[11][21]
%SWITCHAR%- This variable defines the SwitChar to be used for argument parsing by some DR-DOS commands. If defined, it overrides the system's current SwitChar setting. The only accepted characters are "
/" (DOS style), "-" (Unix style) and "[" (CP/M style). See also the relatedCONFIG.SYSdirectiveSWITCHAR(to set the system's SwitChar setting) and the%/%system information variable in some issues of DR-DOSCOMMAND.COM(to retrieve the current setting for portable batchjobs).
%TASKMGRWINDIR%- This variable specifies the directory, where the Windows
SYSTEM.INIto be used by the DR-DOSTASKMGRmultitasker is located, overriding the default procedure to locate the file.[11]
%VER%- This variable contains the version of the operating system in order to distinguish between different versions of DR-DOS in batch jobs and in the display of the
VERcommand.[21] It is also used for the$Vtoken of thePROMPTcommand and affects the value returned by the system information variable%OS_VERSION%. Known values include "1.0" (PalmDOS 1.0), "1.2" (DOS Plus 1.2 in DOS emulation), "2.0" (Concurrent DOS 386 2.0), "3.0" (Concurrent DOS 386 3.0), "3.31" (DR DOS 3.31), "3.32" (DR DOS 3.32), "3.33" (DR DOS 3.33), "3.34" (DR DOS 3.34), "3.35" (DR DOS 3.35), "3.40" (DR DOS 3.40), "3.41" (DR DOS 3.41, EZ-DOS 3.41), "3.41T" (DR DOS 3.41T), "4.1" (Concurrent PC DOS 4.1), "5.0" (DR DOS 5.0, DR Multiuser DOS 5.0), "5.1" (Novell DR Multiuser DOS 5.1), "6.0" (DR Concurrent DOS XM 6.0, DR DOS 6.0), "6.2" (DR Concurrent DOS XM 6.2), "7" (Novell DOS 7, Caldera OpenDOS 7.01, DR-DOS 7.02-7.05), "7.00" (CCI Multiuser DOS 7.00), "7.07" (DR-DOS 7.07), "7.1" (IMS Multiuser DOS 7.1), "7.21" (CCI Multiuser DOS 7.21),[23] "7.22" (CCI Multiuser DOS 7.22) etc.[11][25][23]
%YESCHAR%- This variable can be used to define the character displayed by some commands in messages for "Yes" in
[Y,N]queries, thereby overriding the current system default (typically "Y" in English versions of DR-DOS). If it contains a string, only the first character, uppercased, will be taken. Some commands also support a command line parameter/Yto automatically assume "Yes" on queries, thereby suppressing such prompts. If, however, the parameter/Y:yis used to specify the "Yes" character (thereby overriding any%YESCHAR%setting), queries are not suppressed. See also the relatedCONFIG.SYSdirectiveYESCHARand the environment variable%NOCHAR%.[22]
%$CLS%- This variable defines the control sequence to be sent to the console driver to clear the screen when the
CLScommand is issued, thereby overriding the internal default ("←[2J" under DR-DOS, "←E" under DOS Plus 1.2 on Amstrad machines[19] as well as under Concurrent DOS, Multiuser DOS, and REAL/32 for VT52 terminals, or "←+" under Multiuser DOS for ASCII terminals).[23] If the variable is not defined and noANSI.SYSconsole driver is detected, the DR-DOSCOMMAND.COMwill directly clear the screen viaINT 10h/AH=00hBIOS function, like MS-DOS/PC DOSCOMMAND.COMdoes. A special\nnn-notation for octal numbers is supported to allow the definition of special characters like ESC (ASCII-27 = "←" = 1Bh = 33o), as f.e. inSET $CLS=\033[2J. To send the backslash ("\") itself, it can be doubled "\\".[11][20][23]
%$DIR%- Supported by DOS Plus accepting the values "L" (long) or "W" (wide) to change the default layout of directory listings with DIR. Can be overridden using the command line options
/Lor/W.[20][19] See also the similar environment variable%DIRCMD%and theDIRoptions/Cand/Rof the DR-DOS COMMAND.COM.[11]
%$PAGE%- Supported by DOS Plus accepting the values "
ON" or "OFF" for pagination control. Setting this to "ON" has the same affect as adding/Pto commands supporting it (like DIR or TYPE).[20][19]
%$LENGTH%- Used by DOS Plus to define the screen length of the console in lines. This is used to control in a portable way when the screen output should be temporarily halted until a key is pressed in conjunction with the
/Poption supported by various commands or with automatic pagnination.[20][19] See also the related environment variables%$WIDTH%and%DIRSIZE%as well as the similar pseudo-variable%_ROWS%.
%$WIDTH%- Used by DOS Plus to define the screen width of the console in columns. This is used to control in a portable way the formatting of the screen output of commands like
DIR /WorTYPE filename.[20][19] See also the related environment variables%$LENGTH%and%DIRSIZE%as well as the similar pseudo-variable%_COLUMNS%.
%$SLICE%- Used by DOS Plus accepting a numerical value to control the foreground/background time slicing of multitasking programs.[20][19] See also the DOS Plus command
SLICE.
%$ON%- This variable can hold an optional control sequence to switch text highlighting, reversion or colorization on. It is used to emphasize or otherwise control the display of the file names in commands like
TYPE wildcard, for exampleSET $ON=\033[1mwith ANSI.SYS loaded orSET $ON=\016for an IBM or ESC/P printer. For the special\nnnoctal notation supported, see%$CLS%.[11][19] While the variable is undefined by default under DOS Plus and DR-DOS, the Multiuser DOS default for an ASCII terminal equalsSET $ON=\033p.[20][23] See also the related environment variable%$OFF%.
%$OFF%- This variable can hold an optional control sequence to switch text highlighting, reversion or colorization off. It is used to return to the normal output after the display of file names in commands like
TYPE wildcard, for exampleSET $OFF=\033[0mwith ANSI.SYS loaded orSET $OFF=\024for an IBM or ESC/P printer. For the special\nnnoctal notation supported, see%$CLS%.[11][19] While the variable is undefined by default under DOS Plus and DR-DOS, the Multiuser DOS default for an ASCII terminal equalsSET $OFF=\033q.[20][23] See also the related environment variable%$ON%.
%$HEADER%- This variable can hold an optional control sequence issued before the output of the file contents in commands like
TYPEunder DR-DOS 7.02 and higher. It can be used for highlighting, pagination or formatting, f.e. when sending the output to a printer, i.e.SET $HEADER=\017for an IBM or ESC/P printer. For the special\nnnoctal notation supported, see%$CLS%.[20] See also the related environment variable%$FOOTER%.
%$FOOTER%- This variable can hold an optional control sequence issued after the output of the file contents in commands like
TYPEunder DR-DOS 7.02 and higher. It is used to return to the normal output format, i.e.SET $FOOTER=\022\014in the printer example above. For the special\nnnoctal notation supported, see%$CLS%.[20] See also the related environment variable%$HEADER%.
Datalight ROM-DOS supports a number of additional standard environment variables as well including:
%DIRSIZE%- This variable is used to define non-standard screen sizes
rows[,cols]forDIRoptions/Pand/W(similar to%$LENGTH%and%$WIDTH%under DOS Plus).[18]
%NEWFILE%- This variable is automatically set to the first parameter given to the CONFIG.SYS directive NEWFILE.[18]
%TZ%, %COMM%, %SOCKETS%, %HTTP_DIR%, %HOSTNAME% and %FTPDIR% are also used by ROM-DOS.[18]
OS/2
[edit]%BEGINLIBPATH%- Contains a semicolon-separated list of directories which are searched for DLLs before the directories given by the
%LIBPATH%variable (which is set during system startup with the special CONFIG.SYS directiveLIBPATH). It is possible to specify relative directories here, including "." for the current working directory. See also the related environment variable%ENDLIBPATH%.
%ENDLIBPATH%- a list of directories to be searched for DLLs like
%BEGINLIBPATH%, but searched after the list of directories in%LIBPATH%.
Windows
[edit]These environment variables refer to locations of critical operating system resources, and as such generally are not user-dependent.[26]
%APPDATA%- Contains the full path to the Application Data directory of the logged-in user. Does not work on Windows NT 4.0 SP6 UK.
%LOCALAPPDATA%- This variable is the temporary files of Applications. Its uses include storing of desktop themes, Windows error reporting, caching and profiles of web browsers.
%ComSpec%/%COMSPEC%- The
%ComSpec%variable contains the full path to the command processor; on the Windows NT family of operating systems, this is cmd.exe, while on Windows 9x,%COMSPEC%is COMMAND.COM.
%OS%- The
%OS%variable contains a symbolic name of the operating system family to distinguish between differing feature sets in batchjobs. It resembles an identically named environment variable%OS%found in all DOS-related operating systems of Digital Research-origin like Concurrent DOS, Multiuser DOS, REAL/32, DOS Plus, DR DOS, Novell DOS and OpenDOS.%OS%always holds the string "Windows_NT" on the Windows NT family.[27]
%PATH%- This variable contains a semicolon-delimited (do not put spaces in between) list of directories in which the command interpreter will search for an executable file that matches the given command. Environment variables that represent paths may be nested within the
%PATH%variable, but only at one level of indirection. If this sub-path environment variable itself contains an environment variable representing a path,%PATH%will not expand properly in the variable substitution. Equivalent to the Unix$PATHvariable.
%PROCESSOR_ARCHITECTURE%,%PROCESSOR_ARCHITEW6432%,%PROCESSOR_IDENTIFIER%,%PROCESSOR_LEVEL%,%PROCESSOR_REVISION%- These variables contain details of the CPU; they are set during system installation.
%PUBLIC%- The
%PUBLIC%variable (introduced with Vista) points to the Public (pseudo) user profile directory "C:\Users\Public".
%ProgramFiles%,%ProgramFiles(x86)%,%ProgramW6432%- The
%ProgramFiles%variable points to the Program Files directory, which stores all the installed programs of Windows and others. The default on English-language systems is "C:\Program Files". In 64-bit editions of Windows (XP, 2003, Vista), there are also%ProgramFiles(x86)%, which defaults to "C:\Program Files (x86)", and%ProgramW6432%, which defaults to "C:\Program Files". The%ProgramFiles%itself depends on whether the process requesting the environment variable is itself 32-bit or 64-bit (this is caused by Windows-on-Windows 64-bit redirection[28]).
%CommonProgramFiles%,%CommonProgramFiles(x86)%,%CommonProgramW6432%- This variable points to the Common Files subdirectory of the Program Files directory. The default on English-language systems is "
C:\Program Files\Common Files". In 64-bit editions of Windows (XP, 2003, Vista), there are also%ProgramFiles(x86)%, which defaults to "C:\Program Files (x86)", and%ProgramW6432%, which defaults to "C:\Program Files". The%ProgramFiles%itself depends on whether the process requesting the environment variable is itself 32-bit or 64-bit (this is caused by Windows-on-Windows 64-bit redirection).
%OneDrive%- The
%OneDrive%variable is a special system-wide environment variable found on Windows NT and its derivatives. Its value is the path of where (if installed and setup) the Onedrive directory is located. The value of%OneDrive%is in most cases "C:\Users\{Username}\OneDrive\".
%SystemDrive%- The
%SystemDrive%variable is a special system-wide environment variable found on Windows NT and its derivatives. Its value is the drive upon which the system directory was placed. The value of%SystemDrive%is in most cases "C:".
%SystemRoot%- The
%SystemRoot%variable is a special system-wide environment variable found on the Windows NT family of operating systems. Its value is the location of the system directory, including the drive and path. The drive is the same as%SystemDrive%and the default path on a clean installation depends upon the version of the operating system. By default:- Windows XP and newer versions use "
\WINDOWS". - Windows 2000, NT 4.0 and NT 3.1 use "
\WINNT". - Windows NT 3.5 and NT 3.51 uses "
\WINNT35". - Windows NT 4.0 Terminal Server uses "
\WTSRV".
- Windows XP and newer versions use "
%windir%- This variable points to the Windows directory. (On the Windows NT family of operating systems, it is identical to the
%SystemRoot%variable). Windows 95–98 and Windows ME are, by default, installed in "C:\Windows". For other versions of Windows, see the%SystemRoot%entry above.
User management variables[citation needed] store information related to resources and settings owned by various user profiles within the system. As a general rule, these variables do not refer to critical system resources or locations that are necessary for the OS to run.
%ALLUSERSPROFILE%(%PROGRAMDATA%since Windows Vista)- This variable expands to the full path to the All Users profile directory. This profile contains resources and settings that are used by all system accounts. Shortcut links copied to the All Users\' Start menu or Desktop directories will appear in every user's Start menu or Desktop, respectively.
%USERDOMAIN%- The name of the Workgroup or Windows Domain to which the current user belongs. The related variable,
%LOGONSERVER%, holds the hostname of the server that authenticated the current user's login credentials (name and password). For home PCs and PCs in a workgroup, the authenticating server is usually the PC itself. For PCs in a Windows domain, the authenticating server is a domain controller (a primary domain controller, or PDC, in Windows NT 4-based domains).
%USERPROFILE%- A special system-wide environment variable found on Windows NT and its derivatives. Its value is the location of the current user's profile directory, in which is found that user's HKCU registry hive (
NTUSER). Users can also use the%USERNAME%variable to determine the active users login identification.
Optional System variables[citation needed] are not explicitly specified by default but can be used to modify the default behavior of certain built-in console commands. These variables also do not need to be explicitly specified as command line arguments.
Default values
[edit]The following tables shows typical default values of certain environment variables under English versions of Windows as they can be retrieved under CMD.
(Some of these variables are also defined when running COMMAND.COM under Windows, but differ in certain important details: Under COMMAND.COM, the names of environment variable are always uppercased. Some, but not all variables contain short 8.3 rather than long file names. While some variables present in the CMD environment are missing, there are also some variables specific to the COMMAND environment.)
| Variable | Locale specific | Windows XP (CMD) | Windows Vista and later (CMD) |
|---|---|---|---|
| %ALLUSERSPROFILE%[29] | Yes | C:\Documents and Settings\All Users | C:\ProgramData[29] |
| %APPDATA%[29] | Yes | C:\Documents and Settings\%USERNAME%\Application Data | C:\Users\%USERNAME%\AppData\Roaming[29] |
| %CommonProgramFiles%[29] | Yes | C:\Program Files\Common Files | C:\Program Files\Common Files[29] |
| %CommonProgramFiles(x86)%[29] | Yes | C:\Program Files (x86)\Common Files (only in 64-bit version) | C:\Program Files (x86)\Common Files (only in 64-bit version)[29] |
| %CommonProgramW6432%[29] | Yes | %CommonProgramW6432% (not supported, not replaced by any value) | C:\Program Files\Common Files (only in 64-bit version)[29] |
| %COMPUTERNAME% | No | {computername} | {computername} |
| %ComSpec% | No | C:\Windows\System32\cmd.exe | C:\Windows\System32\cmd.exe |
| %HOMEDRIVE%[29] | No | C: | C:[29] |
| %HOMEPATH%[29] | Yes | \Documents and Settings\%USERNAME% | \Users\%USERNAME%[29] |
| %LOCALAPPDATA%[29] | Yes | %LOCALAPPDATA% (not supported, not replaced by any value) | C:\Users\%USERNAME%\AppData\Local[29] |
| %LOGONSERVER% | No | \\{domain_logon_server} | \\{domain_logon_server} |
| %PATH% | Yes | C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;{plus program paths} | C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;{plus program paths} |
| %PATHEXT% | No | .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.WSF;.WSH | .com;.exe;.bat;.cmd;.vbs;.vbe;.js;.jse;.wsf;.wsh;.msc |
| %ProgramData%[29] | Yes | %ProgramData% (not supported, not replaced by any value) | %SystemDrive%\ProgramData[29] |
| %ProgramFiles%[29] | Yes | %SystemDrive%\Program Files | %SystemDrive%\Program Files[29] |
| %ProgramFiles(x86)%[29] | Yes | %SystemDrive%\Program Files (x86) (only in 64-bit version) | %SystemDrive%\Program Files (x86) (only in 64-bit version)[29] |
| %ProgramW6432%[29] | Yes | %ProgramW6432% (not supported, not replaced by any value) | %SystemDrive%\Program Files (only in 64-bit version)[29] |
| %PROMPT% | No | Code for current command prompt format, usually $P$G
|
Code for current command prompt format, usually $P$G
|
| %PSModulePath% | %PSModulePath% (not supported, not replaced by any value) | %SystemRoot%\system32\WindowsPowerShell\v1.0\Modules\ | |
| %PUBLIC%[29] | Yes | %PUBLIC% (not supported, not replaced by any value) | %SystemDrive%\Users\Public[29] |
| %SystemDrive%[29] | No | C: | C:[29] |
| %SystemRoot%[29] | No | The Windows directory, usually C:\Windows, formerly C:\WINNT | %SystemDrive%\Windows[29] |
| %TEMP%[29] and %TMP%[29] | Yes | %SystemDrive%\Documents and Settings\%USERNAME%\Local Settings\Temp | %SystemRoot%\TEMP (for system environment variables %TMP% and %TEMP%), %USERPROFILE%\AppData\Local\Temp[29] (for user environment variables %TMP% and %TEMP%) |
| %USERDOMAIN% | No | {userdomain} | {userdomain} |
| %USERNAME% | No | {USERNAME} | {USERNAME} |
| %USERPROFILE%[29] | Yes | %SystemDrive%\Documents and Settings\%USERNAME% | %SystemDrive%\Users\%USERNAME% [29] |
| %windir%[29] | No | %SystemDrive%\WINDOWS | %SystemDrive%\Windows[29] |
In this list, there is no environment variable that refers to the location of the user's My Documents directory, so there is no standard method for setting a program's home directory to be the My Documents directory.
Pseudo-environment variables
[edit]The command processors in DOS and Windows also support pseudo-environment variables. These are values that are fetched like environment variables, but are not truly stored in the environment but computed when requested.
DOS
[edit]Besides true environment variables, which are statically stored in the environment until changed or deleted, a number of pseudo-environment variables exist for batch processing.
The so-called replacement parameters or replaceable parameters (Microsoft / IBM terminology) aka replacement variables (Digital Research / Novell / Caldera terminology)[21] or batch file parameters (JP Software terminology)[10] %1..%9 and %0 can be used to retrieve the calling parameters of a batchjob, see SHIFT. In batchjobs, they can be retrieved just like environment variables, but are not actually stored in the environment.
Some command-line processors (like DR-DOS COMMAND.COM,[21] Multiuser DOS MDOS.COM/TMP.EXE (Terminal Message Process), JP Software 4DOS, 4OS2, Take Command (formerly 4NT) and Windows cmd.exe) support a type of pseudo-environment variables named system information variables (Novell / Caldera terminology)[21] or internal variables (JP Software terminology),[10] which can be used to retrieve various possibly dynamic, but read-only information about the running system in batch jobs. The returned values represent the status of the system in the moment these variables are queried; that is, reading them multiple times in a row may return different values even within the same command; querying them has no direct effect on the system. Since they are not stored in the environment, they are not listed by SET and do not exist for external programs to retrieve. If a true environment variable of the same name is defined, it takes precedence over the corresponding variable until the environment variable is deleted again. They are not case-sensitive.
While almost all such variables are prefixed with an underscore ("_") by 4DOS etc. by convention (f.e. %_SECOND%),[10] they are not under DR-DOS COMMAND.COM (f.e. %OS_VERSION%).
In addition, 4DOS, 4OS2, 4NT, and Take Command also support so called variable functions,[10] including user-definable ones. They work just like internal variables, but can take optional parameters (f.e. %@EVAL[]%) and may even change the system status depending on their function.
System information variables supported by DR-DOS COMMAND.COM:
%AM_PM%- This pseudo-variable returns the ante- or post-midday status of the current time. The returned string depends on the locale-specific version of DR-DOS, f.e. "
am" or "pm" in the English version. It resembles an identically named identifier variable in Novell NetWare login scripts.
%DAY%- This pseudo-variable returns the days of the current date in a 2-digit format with leading zeros, f.e. "
01".."31". See also the similar pseudo-variable%_DAY%. It resembles an identically named identifier variable in Novell NetWare login scripts.
%DAY_OF_WEEK%- This pseudo-variable returns the day name of the week in a 3-character format. The returned string depends on the locale-specific version of DR-DOS, f.e. "
Sun", "Mon", "Tue", "Wed", "Thu", "Fri", or "Sat" in the English version. It resembles an identically named identifier variable in Novell NetWare login scripts.
%ERRORLEVEL%- In
COMMAND.COMof DR-DOS 7.02 and higher, this pseudo-variable returns the last error level returned by an external program or theRETURNcommand, f.e. "0".."255".[30][31] See also the identically named pseudo-variable%ERRORLEVEL%under Windows and theIF ERRORLEVELconditional command.
%ERRORLVL%- In DR-DOS 7.02 and higher, this pseudo-variable returns the last error level in a 3-digit format with leading zeros, f.e. "
000".."255".[30][31] Under Multiuser DOS, this is a true environment variable automatically updated by the shell to the return code of exiting programs.[23] See also the related pseudo-variable%ERRORLEVEL%under DR-DOS and theIF ERRORLEVELcommand.
%GREETING_TIME%- This pseudo-variable returns the 3-level day greeting time. The returned string depends on the locale-specific version of DR-DOS, f.e. "
morning", "afternoon", or "evening" in the English version. It resembles an identically named identifier variable in Novell NetWare login scripts.
%HOUR%- This pseudo-variable returns the hours of the current time in 12-hour format without leading zeros, f.e. "
1".."12". It resembles an identically named identifier variable in Novell NetWare login scripts.
%HOUR24%- This pseudo-variable returns the hours of the current time in 24-hour format in a 2-digit format with leading zeros, f.e. "
00".."23". It resembles an identically named identifier variable in Novell NetWare login scripts. See also the similar pseudo-variable%_HOUR%.
%MINUTE%- This pseudo-variable returns the minutes of the current time in a 2-digit format with leading zeros, f.e "
00".."59". It resembles an identically named identifier variable in Novell NetWare login scripts. See also the similar pseudo-variable%_MINUTE%.
%MONTH%- This pseudo-variable returns the months of the current date in a 2-digit format with leading zeros, f.e. "
01".."12". It resembles an identically named identifier variable in Novell NetWare login scripts. See also the similar pseudo-variable%_MONTH%.
%MONTH_NAME%- This pseudo-variable returns the month name of the current date. The returned string depends on the locale-specific version of DR-DOS, f.e. "
January", "February", "March", "April", "May", "June", "July", "August", "September", "October", or "December" in the English version. It resembles an identically named identifier variable in Novell NetWare login scripts.
%NDAY_OF_WEEK%- This pseudo-variable returns the number of day of the current week, f.e. "
1".."7" (with "1" for Sunday). It resembles an identically named identifier variable in Novell NetWare login scripts.
%OS_VERSION%- This pseudo-variable returns the version of the operating system depending on the current setting of the environment variable
%VER%. If%VER%is not defined,%OS_VERSION%returns "off". It resembles an identically named identifier variable in Novell NetWare login scripts, which may return versions also for non-DR-DOS versions of DOS.
%SECOND%- This pseudo-variable returns the seconds of the current time in a 2-digit format with leading zeros, f.e. "
00".."59". It resembles an identically named identifier variable in Novell NetWare login scripts. See also the similar pseudo-variable%_SECOND%.
%SHORT_YEAR%- This pseudo-variable returns the year of the current date in a 2-digit format with leading zeros, f.e. "
93".."99", "00".."92". It resembles an identically named identifier variable in Novell NetWare login scripts.
%YEAR%and%_YEAR%- Supported since Novell DOS 7, the
%YEAR%pseudo-variable returns the year of the current date in a 4-digit format, f.e. "1980".."2099". It resembles an identically named identifier variable in Novell NetWare login scripts. DR-DOS 7.02 and higher added%_YEAR%for compatibility with 4DOS, returning the same value.[10]
%/%- In
COMMAND.COMof DR-DOS 7.02 and higher, this pseudo-variable returns the current SwitChar setting of the system, either "/" (DOS style) or "-" (Unix style).[32][33] See also the relatedCONFIG.SYSdirective SWITCHAR and the environment variable%SWITCHAR%.
%_CODEPAGE%- This pseudo-variable returns the systems' current code page ("
1".."65533"), f.e. "437", "850", "858". This variable was originally introduced by 4DOS,[10] but also became available withCOMMAND.COMsince DR-DOS 7.02. See also theCHCPcommand.
%_COLUMNS%- This pseudo-variable returns the current number of screen columns depending on the display mode, f.e. "
40", "80", "132", etc. This variable was originally introduced by 4DOS,[10] but also became available withCOMMAND.COMsince DR-DOS 7.02. See also a similar environment variable%$WIDTH%under DOS Plus.
%_COUNTRY%- This pseudo-variable returns the systems' current country code ("
1".."65534"), f.e. "1" for USA, "44" for UK, "49" for Germany, "20049" with ISO 8601, "21049" with ISO 8601 and Euro support.[33][34] This variable was originally introduced by 4DOS,[10] but also became available withCOMMAND.COMsince DR-DOS 7.02. See also theCONFIG.SYSdirectiveCOUNTRY.
%_DAY%- This pseudo-variable returns the days of the current date without leading zeros, f.e. "
1".."31". This variable was originally introduced by 4DOS,[10] but also became available withCOMMAND.COMsince DR-DOS 7.02. See also the similar pseudo-variable%DAY%.
%_HOUR%- This pseudo-variable returns the hours of the current time in 24-hour format without leading zeros, f.e. "
0".."23". This variable was originally introduced by 4DOS,[10] but also became available withCOMMAND.COMsince DR-DOS 7.02. See also the similar pseudo-variable%HOUR24%.
%_MINUTE%- This pseudo-variable returns the minutes of the current time without leading zeros, f.e "
0".."59". This variable was originally introduced by 4DOS,[10] but also became available withCOMMAND.COMsince DR-DOS 7.02. See also the similar pseudo-variable%MINUTE%.
%_MONTH%- This pseudo-variable returns the months of the current date without leading zeros, f.e. "
1".."12". This variable was originally introduced by 4DOS,[10] but also became available withCOMMAND.COMsince DR-DOS 7.02. See also the similar pseudo-variable%MONTH%.
%_ROWS%- This pseudo-variable returns the current number of screen rows depending on the display mode, f.e. "
25", "43", "50", etc. This variable was originally introduced by 4DOS,[10] but also became available withCOMMAND.COMsince DR-DOS 7.02. See a similar environment variable%$LENGTH%under DOS Plus.
%_SECOND%- This pseudo-variable returns the seconds of the current time without leading zeros, f.e. "
0".."59". This variable was originally introduced by 4DOS,[10] but also became available withCOMMAND.COMsince DR-DOS 7.02. See also the similar pseudo-variable%SECOND%.
System information variables supported by DR-DOS COMMAND.COM with networking loaded:
%LOGIN_NAME%- This pseudo-variable returns the user name. This always worked with
NETX, but it will also work with Personal NetWare's ODI/VLM if the current drive is a PNW-mapped drive (otherwise an empty string is returned). See also the similarly named environment variable%LOGINNAME%.
%P_STATION%- This pseudo-variable returns the physical station number in a format "
????????????". The value depends on the MAC address of the network adapter, but can be overridden. It resembles an identically named identifier variable in Novell NetWare login scripts.
%STATION%- This pseudo-variable returns the logical station number starting with "
1" for the first client. The numbers are assigned by the file server and remain static for as long as the IPX connection remains established. It resembles an identically named identifier variable in Novell NetWare login scripts.
%FULL_NAME%- This pseudo-variable returns the full name of the logged in user, if available. It resembles an identically named identifier variable in Novell NetWare login scripts. See also the related pseudo-variable
%LOGIN_NAME%.
Windows
[edit]Dynamic environment variables (also named internal variables or system information variables under DOS) are pseudo-environment variables supported by CMD.EXE when command-line extensions are enabled, and they expand to various discrete values whenever queried, that is, their values can change when queried multiple times even within the same command. While they can be used in batch jobs and at the prompt, they are not stored in the environment. Consequently, they are neither listed by SET nor do they exist for external programs to read. They are not case-sensitive.
Indirectly, they are also supported under Windows' COMMAND.COM, which has been modified to internally call CMD.EXE to execute the commands.
%CD%- This pseudo-variable expands to the current directory equivalent to the output of the command
CDwhen called without arguments. While a long filename can be returned underCMD.EXEdepending on the current directory, the fact that the current directory will always be in 8.3 format underCOMMAND.COMwill cause it to return a short filename underCOMMAND.COM, even whenCOMMANDinternally callsCMD.
%CMDCMDLINE%- This pseudo-variable expands to the original startup parameters of
CMD.EXE, f.e. "C:\Windows\system32\cmd.exe". Under Windows'COMMAND.COM, this may return something like "C:\Windows\system32\cmd.exe /c ..." due to the fact thatCOMMAND.COMcallsCMD.EXEinternally.
%CMDEXTVERSION%- This pseudo-variable expands to the version of the command-line extensions of
CMD.EXE, if enabled (e.g. "1" under Windows NT, "2" under Windows 2000 and Windows XP).
%DATE%- This pseudo-variable expands to the current date. The date is displayed according to the current user's date format preferences.
%ERRORLEVEL%- This pseudo-variable expands to the last set error level, a value between "
0" and "255" (without leading zeros).[30][35][31] External commands and some internal commands set error levels upon execution. See also the identically named pseudo-variable%ERRORLEVEL%under DR-DOS and theIF ERRORLEVELcommand.
%HIGHESTNUMANODENUMBER%- This pseudo-variable returns the number of the highest NUMA node.
%RANDOM%- This pseudo-variable returns a random number between "
0" and "32767".
%TIME%- This pseudo-variable returns the current time. The time is displayed according to the current user's time format preferences. If the
%TIME%and%DATE%variables are both used, it is important to read them both in this particular order in rapid succession in order to avoid midnight-rollover problems.
Other shells
[edit]Unix-like shells have similar dynamically generated variables, bash's $RANDOM being a well-known example. However, since these shells have a concept of local variables, they are described as special local variables instead.[36]
See also
[edit]Notes
[edit]- ^ a b Applications not coping properly with environment variables longer than 128 characters include CadStar PCB, Checkit, Computer Select CD-ROM, RenderMan, VINES Network, Windows 3.0, and Word for Windows 6.0.
- ^ 4DOS and MS-DOS 7.0 set the length to 127 and insert ASCII-13 at this position, but Borland libraries set the length to the invalid value of 128 and do not insert an ASCII-13. For shorter command lines, 4DOS/NDOS and DR-DOS also insert an ASCII-0 after the ASCII-13, but not when invoked via INSTALL directive; MS-DOS does not.
References
[edit]- ^ Robbins, Arnold; Beebe, Nelson H. F. (May 2005). Apandi, Tatiana; Randal, Allison; Witwer, Adam (eds.). Classic Shell Scripting (1 ed.). O'Reilly. ISBN 978-0-596-00595-5.
- ^ "unset - unset values and attributes of variables and functions – ". Commands & Utilities Reference, The Single UNIX Specification - The Open Group Base Specifications, IEEE Std 1003.1-2008 (Issue 7 ed.). The IEEE and The Open Group. 2016 [2001]. Archived from the original on 2017-12-18. Retrieved 2017-12-18.
- ^ fgrose (2015-07-31) [2011]. "The unset builtin command". Bash Hackers Wiki. Archived from the original on 2017-12-18. Retrieved 2017-12-18.
- ^ Jacobs, Mike; Koren, Alexander; Satran, Michael (2017-11-14). "Store and retrieve settings and other app data". Microsoft. Archived from the original on 2017-12-18. Retrieved 2017-12-18.
- ^ Raymond, Eric (2002-08-02) [Originally published 2001]. "The BROWSER project". Archived from the original on 2019-09-21. Retrieved 2020-10-21.
- ^ "LWN - Development". LWN.net. 2001-02-01. Archived from the original on 2019-02-08. Retrieved 2020-10-21.
Standardizing a BROWSER environment variable. Eric Raymond is promoting the use of a new environment variable, BROWSER, to complement the existing PAGER, MAILER, and EDITOR variables. This effort is being tested as an experiment in hacking social systems.
- ^ Špaček, Michal (2020-01-19) [First version published 2013]. "Env::Browser-0.06". metacpan.org. Archived from the original on 2020-10-21. Retrieved 2020-10-21.
Env::Browser - Process environment variable $BROWSER and run web browser
- ^ "webbrowser — Convenient Web-browser controller". docs.python.org. Archived from the original on 2020-10-13. Retrieved 2020-10-21.
- ^ "DefaultWebBrowser - Debian Wiki". wiki.debian.org. 2020-06-10. Archived from the original on 2020-10-21. Retrieved 2020-10-21.
The environment variable BROWSER can be set to[…] always choose your desired browser.
- ^ a b c d e f g h i j k l m n o p q r s t u v w x y z aa ab Brothers, Hardin; Rawson, Tom; Conn, Rex C.; Paul, Matthias R.; Dye, Charles E.; Georgiev, Luchezar I. (2002-02-27). 4DOS 8.00 online help.
- ^ a b c d e f g h i j k l m n o p q r Paul, Matthias R. (1997-07-30) [1994-05-01]. NWDOS-TIPs — Tips & Tricks rund um Novell DOS 7, mit Blick auf undokumentierte Details, Bugs und Workarounds. Release 157 (in German) (3 ed.). Archived from the original on 2016-11-04. Retrieved 2014-08-06.
{{cite book}}:|work=ignored (help) (NB. NWDOSTIP.TXT is a comprehensive work on Novell DOS 7 and OpenDOS 7.01, including the description of many undocumented features and internals. The provided link points to a HTML-converted version of the file, which is part of theMPDOSTIP.ZIPcollection.) [1] - ^ a b c d e Paul, Matthias R. (1997-05-01) [1995-03-01]. "Hinweise zu JPSofts 4DOS 5.5b/c, 5.51, 5.52a und NDOS". MPDOSTIP (in German). Archived from the original on 2016-11-04. Retrieved 2015-05-08. (NB. The provided link points to a HTML-converted version of the
4DOS5TIP.TXTfile, which is part of theMPDOSTIP.ZIPcollection.) [2] - ^ a b Paul, Matthias R. (1997-10-02). "Caldera OpenDOS 7.01/7.02 Update Alpha 3 IBMBIO.COM README.TXT". Archived from the original on 2003-10-04. Retrieved 2009-03-29. [3]
- ^ Paul, Matthias R. (1997-05-27) [1996]. "SETENV v1.11". Archived from the original on 2009-02-15. Retrieved 2019-08-09.
[…] SETENV […] to hide and later restore the […] pre-environment […] By using SETENV.COM you can save some KiloBytes of rare DOS memory […] depending on the number of drivers loaded by INSTALL=/INSTALLHIGH=/HIINSTALL= and the current size of the pre-environment. […] this original […] feature cannot be found in any known memory manager/optimizer. […]
- ^ Paul, Matthias R. (2002-04-06). "Re: [fd-dev] ANNOUNCE: CuteMouse 2.0 alpha 1". freedos-dev. Archived from the original on 2020-02-07. Retrieved 2020-02-07.
[…] In CTMOUSE.ASM prepareTSR routine I found a comment in regard to the zero-environment. […] DESQview or DRDOS zero-env? […] release environment block […] skip if any problem […] zero-pad for MEM style utilities […]
- ^ "PTS-DOS 2000 Pro User Manual" (PDF). Archived (PDF) from the original on 2018-05-12. Retrieved 2018-05-12.
- ^ Paul, Matthias R. (2002-10-07). "Re: Run a COM file". Newsgroup: alt.msdos.programmer. Archived from the original on 2017-09-03. Retrieved 2017-09-03. [4]
- ^ a b c d e f Datalight, Inc.; GPvNO (April 2005) [1999]. "Datalight ROM-DOS User's Guide" (PDF). Datalight, Inc. 3010-0200-0716. Archived (PDF) from the original on 2019-03-20. Retrieved 2018-09-16.
- ^ a b c d e f g h i Kotulla, Martin (November 1987). "Von CP/M zu MS-DOS, Teil 11" (PDF). Professional Computing (PC) - Schneider International (in German). 3 (11): 100–103. Archived (PDF) from the original on 2019-04-24. Retrieved 2018-05-20.
- ^ a b c d e f g h i j k l m n Paul, Matthias R. (2002-03-26). "Updated CLS posted". freedos-dev mailing list. Archived from the original on 2018-10-04. Retrieved 2014-08-06.
- ^ a b c d e f g h Caldera DR-DOS 7.02 User Guide. Caldera, Inc. 1998 [1993, 1997]. Archived from the original on 2016-11-04. Retrieved 2013-08-10.
- ^ a b c d Paul, Matthias R. (2017-08-14) [2017-08-07]. "The continuing saga of Windows 3.1 in enhanced mode on OmniBook 300". MoHPC - the Museum of HP Calculators. Archived from the original on 2018-05-01. Retrieved 2018-05-01.
[…] set DRSYS=ON (optional to tell SYS you are aware of the fact that you're running it in a foreign environment and want to proceed anyway without having to individually ACK some warnings and extra info screens displayed in this scenario otherwise) […]
- ^ a b c d e f g h i CCI Multiuser DOS 7.22 GOLD Online Documentation. Concurrent Controls, Inc. (CCI). 1997-02-10. HELP.HLP.
- ^ CCI Multiuser DOS 7.22 GOLD Installation Guide. Concurrent Controls, Inc. (CCI). 1997-02-10. PRINTDOC.HLP.
- ^ a b c Paul, Matthias R. (2002-02-20). "How to detect FreeCOM/FreeDOS in-batch?". freedos-dev mailing list. Archived from the original on 2018-11-06. Retrieved 2014-08-06.
- ^ "Recognized environment variables - Windows Deployment". 2024-01-09.
- ^ Brink, Shawn (2018-11-17). "Environment Variables in Windows 10 - Complete List of Environment Variables in Windows 10". Windows Ten Forums. Archived from the original on 2019-03-27. Retrieved 2019-04-24.
- ^ "WOW64 Implementation Details".
- ^ a b c d e f g h i j k l m n o p q r s t u v w x y z aa ab ac ad ae af ag ah ai aj ak Schulz, Hajo (2014-10-02). "Ordner für spezielle Fälle — Die "benannten Ordner" in Windows aus User- und Entwicklersicht" [Special purpose folders — Windows' "named folders" from a user's and developer's perspective]. c't - magazin für computertechnik (in German). 2014 (22). Heise Verlag: 180–184. Archived from the original on 2016-07-09. Retrieved 2019-04-08.
- ^ a b c Paul, Matthias R. (1997-05-01) [1993-10-01]. BATTIPs — Tips & Tricks zur Programmierung von Batchjobs (in German). 7: ERRORLEVEL abfragen. Archived from the original on 2017-08-23. Retrieved 2017-08-23.
{{cite book}}:|work=ignored (help) [5] [6] Archived 2017-09-11 at archive.today (NB. BATTIPS.TXT is part of MPDOSTIP.ZIP. The provided link points to a HTML-converted older version of the BATTIPS.TXT file.) [7] - ^ a b c Auer, Eric; Paul, Matthias R.; Hall, Jim (2015-12-24) [2003-12-31]. "MS-DOS errorlevels". Archived from the original on 2015-12-24.
- ^ Paul, Matthias R. (1998-01-09). DELTREE.BAT R1.01 Extended file and directory delete. Caldera, Inc. Archived from the original on 2019-04-08. Retrieved 2019-04-08.
- ^ a b DR-DOS 7.03 WHATSNEW.TXT — Changes from DR-DOS 7.02 to DR-DOS 7.03. Caldera, Inc. 1998-12-24. Archived from the original on 2019-04-08. Retrieved 2019-04-08.
- ^ Paul, Matthias R. (2001-06-10) [1995]. "DOS COUNTRY.SYS file format" (COUNTRY.LST file) (1.44 ed.). Archived from the original on 2016-04-20. Retrieved 2016-08-20.
- ^ Allen, William; Allen, Linda. "Windows 95/98/ME ERRORLEVELs". Archived from the original on 2011-07-07.
- ^ "Shell Variables". Bash Reference Manual.
Further reading
[edit]- Chen, Raymond (2010-05-06). "What are these strange =C: environment variables?". The New Old Thing. Microsoft. Retrieved 2025-04-03.
External links
[edit]- : user environment – Linux Programmer's Manual – Overview, Conventions and Miscellanea from Manned.org
- – FreeBSD Miscellaneous Information Manual
- – Darwin and macOS Miscellaneous Information Manual
- – Solaris 11.4 Standards, Environments, Macros, Character Sets, and Miscellany Reference Manual
- "Environment Variables Wiki". Archived from the original on 2019-04-27.
- User Environment Variables
- fix setx.exe not found bug
Environment variable
View on GrokipediaNAME=value and can influence utilities, functions, and applications as specified in standards like POSIX.[4]
Environment variables serve multiple purposes, including standardizing shell configurations, managing sensitive data such as API keys or database credentials, and enabling consistent application behavior across different deployment environments like development, staging, and production.[5][6] They promote security by keeping secrets out of hardcoded code and facilitate portability, as the same application can run on various operating systems—such as Linux, Windows, or macOS—by relying on OS-provided variables.[1] Common system-wide variables include PATH, which specifies directories for executable searches; HOME, indicating the user's home directory; and USER, denoting the current username, all of which are typically set by the operating system upon login.[2][7]
To manage environment variables, users and administrators can set them temporarily in a shell session using commands like export NAME=value in Unix shells or set NAME=value in Windows Command Prompt, while permanent settings are configured in profile files such as ~/.bashrc for user-specific variables or /etc/environment for system-wide ones on Linux.[5][8][9] Programs access these variables through language-specific functions, such as getenv() in C or os.environ in Python, retrieving values to configure runtime options like database connections or debug modes.[6] In modern development, tools like .env files or secrets managers further extend their use, loading variables into the environment for containerized or cloud-based applications while adhering to best practices for secure handling.[1]
Introduction
Definition
An environment variable is a dynamic named value maintained by the operating system that affects the behavior of running processes, providing configurable parameters such as paths, locales, or resource limits to influence program execution without modifying the code itself. These variables are passed to a process at startup via its execution environment, allowing applications to query and utilize them for runtime decisions, such as determining file locations or user preferences.[10][11] Environment variables follow a key-value pair structure, where the name (key) is a string typically composed of uppercase letters, digits, and underscores—starting with an uppercase letter—and the value is an arbitrary string that may encode paths, numerical data, or other textual information. This format enables a standardized way to associate settings with processes, with no inherent limit on the number of variables or their individual lengths, though the aggregate size combined with command-line arguments may be constrained by system resources. In C-language programs, the environment is presented as an array of null-terminated strings (environ), terminated by a null pointer, facilitating access through functions like getenv().[10][12] A key distinction exists between environment variables and shell variables: the former are inherited by child processes and accessible system-wide at the process level, while shell variables remain local to the invoking shell session unless explicitly exported to become part of the environment. This separation ensures that only intended configurations propagate to subprocesses, preventing unintended leakage of transient shell state.[13][11] The concept of environment variables originated in early Unix systems during the 1970s, evolving from initial variable mechanisms in shells to a formalized process-level feature by the late decade.[14]Purpose and History
Environment variables serve several primary purposes in computing systems. They enable the configuration of software behavior by allowing applications to adapt to different runtime conditions without requiring recompilation or code modifications, such as specifying database connection strings or log levels.[15] Additionally, they facilitate the storage of temporary data, the passing of information between parent and child processes during execution, and the definition of system paths, exemplified by the PATH variable which directs the operating system to locations for executable files.[16] The concept of environment variables originated in Unix Version 7, released in 1979, where they were introduced through modifications to the exec system call, enabling processes to inherit a set of key-value pairs from their parents.[17] This innovation built on earlier Unix versions by adding a third argument to exec for passing the environment block, a design that persists in modern Unix-like systems.[17] Environment variables were later adopted in PC DOS 2.0 in 1982, primarily to support batch processing and command scripting in the MS-DOS environment, marking their entry into personal computing operating systems.[18] Their evolution continued with Windows NT in 1993, which integrated environment variables with the Windows Registry for persistent storage and management, distinguishing between system-wide and user-specific variables to enhance configurability in multi-user scenarios.[19] A key advantage of environment variables lies in their role in promoting portability across platforms. By externalizing configuration details into environment-specific variables, software can operate consistently on diverse systems—such as Unix, Windows, or cloud environments—without embedding platform-dependent code, thereby simplifying development and deployment.[20] In contemporary computing, environment variables remain essential for scripting, where they enable dynamic parameterization of shell scripts and automation tasks; for application deployment in containerized environments like Docker and Kubernetes, where they manage secrets and settings across development, testing, and production stages; and for environment-specific adaptations, such as toggling debug modes or API endpoints based on the deployment context.[6]Design Principles
Core Concepts
Environment variables form the environment of a process, consisting of a collection of key-value pairs that are passed to the process at its startup by the operating system or a parent process. This environment is stored in process-specific memory structures, such as an array of strings or a contiguous block, allowing the process and its code to access these values dynamically during execution.[12][21] In shell environments, exporting a variable refers to the mechanism by which a shell includes a local variable in its environment, making it available for inheritance by child processes. When a new process is created, it receives a copy of the parent's environment, enabling configuration and state to propagate without direct parameter passing; only variables included in the parent's environment are part of this inheritable set, distinguishing them from non-inheritable local variables. Variables are referenced in commands through expansion and substitution, where the shell or runtime environment replaces a placeholder (such as $NAME in Unix-like shells or %NAME% in Windows) with the variable's actual value before executing the command. This process occurs during parsing, ensuring the resolved value is used in the final command line or script execution, and supports nested or conditional expansions for flexible usage. Operating systems impose limits on the total size of the environment block (combined arguments and variables) and individual variables to manage memory and security. In Unix-like systems, the total is limited by ARG_MAX (typically 128 KB to 2 MB as of 2024, configurable via kernel parameters). In Windows, pre-Vista versions capped the total at 32 KB; from Vista onward, there is no total size limit, though individual variables are limited to 32,767 characters. These constraints ensure efficient process creation but require careful management of variable counts and lengths.[22][23][21]Inheritance and Scope
Environment variables follow an inheritance model where a child process receives a copy of the parent's environment at creation, remaining independent so modifications in the child do not affect the parent or siblings. For example, in Unix-like systems, this occurs via the fork() system call, and the environment can be passed or replaced during exec() invocation; in Windows, CreateProcess copies the environment block unless specified otherwise.[12][24] The scope of environment variables is process-local, visible only to the process and its descendants, but inaccessible to siblings or unrelated processes. Within a shell session, exported variables propagate to subprocesses launched from that shell. For system-wide scope, variables are initialized via OS startup mechanisms, such as profile scripts or configuration files loaded during authentication. Modifications to environment variables, whether through OS-specific APIs (e.g., setenv() in POSIX or SetEnvironmentVariable() in Windows) or shell builtins, apply only to the current process and do not retroactively alter previously created children's environments. This unidirectional inheritance ensures isolation, with changes affecting only future children. The lifetime of environment variables aligns with the process, persisting until exit. For persistence across sessions or reboots, variables are defined in configuration files, such as user profiles or system settings.[25][26]Syntax and Manipulation
Unix-like Systems
In Unix-like systems, environment variables conform to POSIX standards, serving as key-value pairs that convey configuration and state information to processes and their children. These variables are integral to the operating environment, influencing the behavior of utilities, applications, and the shell itself. Unlike transient shell variables, true environment variables are explicitly exported and inherited across process boundaries, ensuring persistence in execution contexts. Several standard environment variables are commonly predefined in Unix-like systems. The HOME variable specifies the pathname of the user's home directory, used by utilities like cd to determine the default directory for navigation. The USER variable (or the POSIX-defined LOGNAME as its equivalent) holds the login name of the current user, aiding in user-specific operations and authentication checks. The SHELL variable identifies the pathname of the user's preferred command interpreter, guiding applications that invoke shells. Additionally, the TERM variable indicates the type of the terminal in which the process is running, enabling terminal-dependent features such as cursor control and screen formatting in tools like tput. These variables are literal strings, requiring no shell-style expansion when accessed, and are directly available to processes upon invocation. System-wide defaults for environment variables are typically established through configuration files processed at system startup or login. The /etc/environment file, parsed by the Pluggable Authentication Modules (PAM) framework in many implementations, sets initial variables for all user sessions and non-interactive processes, supporting simple assignments without shell interpretation. For login shells, profile scripts such as /etc/profile or files in /etc/profile.d/ extend these settings, sourcing additional variables during shell initialization to propagate them to interactive environments. Process-specific overrides occur via the execve() system call, which replaces the current process image and passes an explicit array of environment strings (in name=value format) to the new executable, allowing targeted modifications without altering the parent environment. A key distinction in Unix-like systems lies between shell variables and true environment variables. Shell variables are confined to the current shell instance and its non-exported assignments, ceasing to exist upon shell exit. In contrast, exported environment variables—achieved via the export command—survive the shell's termination and are automatically inherited by child processes, including those launched via execve(), ensuring consistent access across the process tree. This inheritance model supports modular program design while maintaining security boundaries, as parents cannot directly modify child environments post-fork.DOS, OS/2, and Windows
In DOS and OS/2, environment variables are primarily set during system boot using commands in the CONFIG.SYS and AUTOEXEC.BAT files. The SET command in CONFIG.SYS defines variables that apply to the operating system and its applications, storing them in memory for access by programs. For example, common true environment variables include PATH, which specifies directories for executable files and is typically set to include the system directory like C:\DOS, and COMSPEC, which points to the command interpreter such as C:\COMMAND.COM in DOS or the OS/2 shell.[27][9][28] TEMP is another standard variable, directing temporary file storage to a designated directory, often set to C:\TEMP by default. These variables are loaded sequentially from CONFIG.SYS first, followed by AUTOEXEC.BAT, ensuring persistence across sessions unless modified. In OS/2, SET statements in CONFIG.SYS specifically target OS/2 applications, while AUTOEXEC.BAT handles user-level settings like PATH extensions.[29][30][31] In Windows, environment variables follow a similar structure but are managed through the registry for system-wide and user-specific persistence. System environment variables are stored in the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment registry key, loaded at boot to establish defaults applicable to all users. User environment variables are stored in the HKEY_CURRENT_USER\Environment registry key, enabling personalized configurations for the current user without requiring administrative privileges or affecting other users.[21] For most environment variables, a user-defined value overrides the corresponding system default if both are defined. The PATH variable is handled specially to support multi-user systems: the effective PATH is the concatenation of the system PATH followed by the user PATH (separated by semicolons). This separation allows users to extend the executable search path with directories for personally installed tools (such as Python or Git) while preserving access to core system directories (such as C:\Windows\System32) and maintaining global system consistency and security across multiple users.[21] Common true variables include PATH, which by default encompasses directories like %SystemRoot%\system32 and %SystemRoot% in the system PATH, enabling executable discovery; COMSPEC, set to %SystemRoot%\system32\cmd.exe as the command interpreter; TEMP, pointing to %USERPROFILE%\AppData\Local\Temp for temporary files; and SYSTEMROOT, typically C:\Windows, referencing the main system folder.[21][29] Variable expansion in DOS, OS/2, and Windows uses the direct syntax %VAR%, where the percent signs delimit the variable name for substitution without recursive or delayed processing by default. These variables are inherited by child processes, maintaining consistency in execution environments.[9][21]Usage Examples
Basic Operations
Environment variables are typically set for immediate use in a command by prefixing the assignment with the variable name and value, followed by the command that utilizes it, such asVAR=value some_command ${VAR} in shell-based systems. This method exports the variable only to the subprocess running the command, allowing it to reference the value without altering the parent environment.[32]
To view all current environment variables, utilities like env or shell builtins such as set can be invoked, displaying a list of variable names paired with their values in a key-value format. These commands provide a snapshot of the environment block accessible to the process.[33]
Unsetting an environment variable involves using a dedicated command like unset VAR, which removes the variable from the current environment block. Verification of removal can be done by attempting to retrieve the variable's value, which should return empty or indicate it is undefined.[34]
Nested referencing occurs when one environment variable incorporates the value of another during expansion, such as configuring PATH to include ${HOME}/bin:${PATH}, where ${HOME} resolves to the user's home directory path before the full PATH is constructed. This allows dynamic composition of values based on existing variables.[35]
Platform-Specific Cases
In Unix-like systems, such as Linux and macOS, environment variables are manipulated using shell commands likeexport in Bourne-compatible shells (e.g., Bash). A common real-world application is modifying the PATH variable to include a new directory for executable searches, ensuring that subsequent commands can locate programs in the added path without full qualification. For instance, the command export PATH=$PATH:/new/dir appends /new/dir to the existing PATH, and echo $PATH displays the updated value, such as /usr/local/bin:/usr/bin:/new/dir assuming the prior value. Another practical example is determining the current shell on macOS: use the command echo $0 which outputs the name of the running shell, or echo $SHELL for the default login shell.[36][37] This approach is temporary for the current session unless added to a shell configuration file like .bashrc.[38][39]
On Windows, using the Command Prompt (cmd.exe), the SET command assigns values to environment variables, which can then be referenced in commands or batch scripts. A practical example involves setting a temporary directory for applications that require it, such as SET TEMP=C:\temp, followed by echo %TEMP% to verify the assignment (outputting C:\temp) and dir %TEMP% to list its contents, confirming accessibility for file operations. This setting persists only for the current process and its children unless made permanent via system settings.[9][40]
In DOS and early Windows batch files (.bat), the @echo off directive suppresses command echoing for cleaner output, while SET customizes interactive elements like the command prompt. For example, @echo off followed by SET PROMPT=$P$G restores the default prompt displaying the current drive and path (e.g., C:\>) and can be used within loops to maintain consistent feedback during iterative tasks, such as file processing scripts. This configuration enhances usability in automated sequences without altering the core batch logic.[9][41]
Regarding error handling, referencing an undefined environment variable typically results in an empty string expansion rather than an explicit error, allowing scripts to continue execution gracefully. In Unix-like systems, echo $UNDEF outputs nothing (blank line), treating the absence as an empty value. Similarly, in Windows and DOS, echo %UNDEF% produces a blank output, though enclosing in delimiters like echo [%UNDEF%] reveals the empty expansion as [], preventing unintended command interpretation while avoiding runtime halts.[42][43]
True Environment Variables
Unix-like Systems
In Unix-like systems, environment variables conform to POSIX standards, serving as key-value pairs that convey configuration and state information to processes and their children. These variables are integral to the operating environment, influencing the behavior of utilities, applications, and the shell itself. Unlike transient shell variables, true environment variables are explicitly exported and inherited across process boundaries, ensuring persistence in execution contexts. Several standard environment variables are commonly predefined in Unix-like systems. The HOME variable specifies the pathname of the user's home directory, used by utilities like cd to determine the default directory for navigation. The USER variable (or the POSIX-defined LOGNAME as its equivalent) holds the login name of the current user, aiding in user-specific operations and authentication checks. The SHELL variable identifies the pathname of the user's preferred command interpreter, guiding applications that invoke shells. Additionally, the TERM variable indicates the type of the terminal in which the process is running, enabling terminal-dependent features such as cursor control and screen formatting in tools like tput. These variables are literal strings, requiring no shell-style expansion when accessed, and are directly available to processes upon invocation. System-wide defaults for environment variables are typically established through configuration files processed at system startup or login. The /etc/environment file, parsed by the Pluggable Authentication Modules (PAM) framework in many implementations, sets initial variables for all user sessions and non-interactive processes, supporting simple assignments without shell interpretation. For login shells, profile scripts such as /etc/profile or files in /etc/profile.d/ extend these settings, sourcing additional variables during shell initialization to propagate them to interactive environments. Process-specific overrides occur via the execve() system call, which replaces the current process image and passes an explicit array of environment strings (in name=value format) to the new executable, allowing targeted modifications without altering the parent environment. A key distinction in Unix-like systems lies between shell variables and true environment variables. Shell variables are confined to the current shell instance and its non-exported assignments, ceasing to exist upon shell exit. In contrast, exported environment variables—achieved via the export command—survive the shell's termination and are automatically inherited by child processes, including those launched via execve(), ensuring consistent access across the process tree. This inheritance model supports modular program design while maintaining security boundaries, as parents cannot directly modify child environments post-fork.DOS, OS/2, and Windows
In DOS and OS/2, environment variables are primarily set during system boot using commands in the CONFIG.SYS and AUTOEXEC.BAT files. The SET command in CONFIG.SYS defines variables that apply to the operating system and its applications, storing them in memory for access by programs. For example, common true environment variables include PATH, which specifies directories for executable files and is typically set to include the system directory like C:\DOS, and COMSPEC, which points to the command interpreter such as C:\COMMAND.COM in DOS or the OS/2 shell.[27][9][28] TEMP is another standard variable, directing temporary file storage to a designated directory, often set to C:\TEMP by default. These variables are loaded sequentially from CONFIG.SYS first, followed by AUTOEXEC.BAT, ensuring persistence across sessions unless modified. In OS/2, SET statements in CONFIG.SYS specifically target OS/2 applications, while AUTOEXEC.BAT handles user-level settings like PATH extensions.[29][30][31] In Windows, environment variables follow a similar structure but are managed through the registry for system-wide persistence, with user-specific overrides possible. System variables are stored in the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment registry key, loaded at boot to establish defaults. Common true variables include PATH, which by default encompasses directories like %SystemRoot%\system32 and %SystemRoot%, enabling executable discovery; COMSPEC, set to %SystemRoot%\system32[cmd.exe](/page/Cmd.exe) as the command interpreter; TEMP, pointing to %USERPROFILE%\AppData\Local\Temp for temporary files; and SYSTEMROOT, typically C:\Windows, referencing the main system folder.[21][21][29] Variable expansion in DOS, OS/2, and Windows uses the direct syntax %VAR%, where the percent signs delimit the variable name for substitution without recursive or delayed processing by default. These variables are inherited by child processes, maintaining consistency in execution environments.[9][21]Pseudo-Environment Variables
DOS and Windows
In DOS and Windows, pseudo-environment variables serve as dynamic placeholders that the command-line interpreter (COMMAND.COM in DOS or cmd.exe in Windows) expands at runtime during command parsing, providing runtime information without being stored as persistent, inheritable values like true environment variables. These variables mimic the syntax of true environment variables (enclosed in percent signs) but generate their content on-the-fly based on system state, such as the current date or the result of a prior command.[44][45] In DOS, common pseudo-environment variables include %DATE%, which expands to the current system date in the format defined by the DATE command; %TIME%, which provides the current system time in the format set by the TIME command; and %ERRORLEVEL%, which returns the exit code (error level) from the most recently executed program or batch command. For example, after running a program that fails, %ERRORLEVEL% might expand to a non-zero value like 1, allowing conditional logic in batch files via commands like IF ERRORLEVEL 1. These are processed by the COMMAND.COM interpreter and are essential for scripting runtime conditions, though their availability can vary by DOS version, with fuller support in later releases like MS-DOS 6.x.[46] Windows cmd.exe extends these with additional pseudo-variables tailored for batch scripting and dynamic operations. %CD% expands to the current working directory path, %RANDOM% generates a pseudo-random integer between 0 and 32,767 each time it is referenced, and batch-specific modifiers like %~dp0 provide the drive letter and full path to the directory containing the executing batch file (e.g., in a script saved as C:\Scripts\test.bat, %~dp0 yields C:\Scripts). Other modifiers, such as %~d0 for the drive of the batch file or %Other Shells and Systems
In Unix-like shells such as Bash and Zsh, pseudo-environment variables encompass special parameters that provide dynamic runtime information without being part of the persistent environment block. For instance, the parameter$? holds the exit status of the most recently executed foreground pipeline, allowing scripts to check command outcomes immediately after execution.[47] Similarly, $$ expands to the process ID (PID) of the current shell instance, useful for logging or process management within scripts.[47] The tilde character (~), when unquoted at the beginning of a word, undergoes tilde expansion to represent the home directory of the current user, facilitating path shortcuts in commands like cd ~. These features operate analogously in Zsh, where special parameters like $? and $$ are predefined and read-only, ensuring consistent behavior across compatible shells.[48]
Unlike true environment variables, these pseudo-variables are generated on-the-fly by shell builtins or expansion mechanisms during command processing, rather than being stored in the process's environment block passed to child processes.[47] This dynamic computation enables real-time evaluation—such as querying the current PID or exit status—but means they are not inherited or exportable in the same manner as standard variables. In the C shell (csh) and its variant tcsh, equivalent functionality exists with variations; for example, $status captures the exit status of the last command, differing from Bash's $? and highlighting shell-specific syntax.[49]
Beyond Unix variants, other systems feature similar constructs. In PowerShell, automatic variables like $PWD provide the current working directory path, computed dynamically based on the session's location without relying on static storage.[50] In OS/2's command processor (CMD.EXE), pseudo-variables like BeginLIBPath and EndLIBPath support library path management, expanded during command interpretation rather than treated as fixed environment entries.[51]
Portability challenges arise due to these variations; scripts relying on $? in Bash may fail in csh without adjustment to $status, necessitating conditional checks or standardized alternatives for cross-shell compatibility.[49] Such differences underscore the importance of shell-specific documentation when developing portable automation.
Security and Best Practices
Common Risks
Environment variables pose significant security risks due to their visibility and persistence across processes. Sensitive information, such as API keys or database credentials, stored in environment variables can be exposed through system commands likeps or env, allowing unauthorized users with access to the process list to view them.[52] This visibility extends to other processes on the system, potentially enabling attackers to extract secrets if they compromise a shared user context.[53] Additionally, environment variables persist in process memory dumps or core files generated during crashes, making them recoverable even after process termination and increasing the risk of post-incident data exposure.[54]
Injection attacks exploit environment variables by incorporating untrusted input, leading to unintended command execution. For instance, manipulating the PATH variable to include directories containing malicious executables can cause legitimate commands to invoke trojans instead, hijacking execution flow without altering the target binary.[55] Untrusted data in other variables, such as those passed to shell scripts, can enable command injection, where attackers append arbitrary commands that the application executes with elevated privileges.[56] This vulnerability is particularly acute in applications that dynamically construct commands based on environment settings, allowing remote code execution if input validation is absent.[57]
Denial-of-service conditions arise from overly long or numerous environment variables that exhaust system resources. Excessive length in variables like PATH can trigger buffer overflows during processing, causing application crashes or halting execution.[57] Large environment blocks consume significant memory, potentially leading to allocation failures or system-wide slowdowns, especially in resource-constrained environments like containers or embedded systems.[52]
Historical incidents highlight these risks in production environments, particularly web servers. In 2014, the Shellshock vulnerability (CVE-2014-6271) allowed attackers to inject and execute code via specially crafted environment variables in Bash, affecting millions of web servers running CGI scripts and enabling remote command execution.[58] Similarly, the 2021 Codecov supply chain compromise involved attackers modifying a Bash uploader script to exfiltrate environment variables containing secrets from CI/CD pipelines, impacting over 23,000 organizations and exposing API keys used in web applications.[59] More recently, in 2025, CVE-2025-24959 in the ZX JavaScript tool enabled environment variable injection via the dotenv API, allowing arbitrary command execution by injecting unintended variables into process.env.[60] Additionally, CVE-2025-41253 in Spring Cloud Gateway permitted exposure of environment variables and system properties through Spring Expression Language (SpEL) in application routes, risking leakage of secrets in cloud-native setups.[61] These events underscore how environment variable mishandling in web server configurations can lead to widespread data breaches and unauthorized access.
Mitigation Strategies
To mitigate risks associated with environment variables, particularly for sensitive data, one primary strategy is to avoid their use altogether when possible. Instead, store sensitive information such as API keys, passwords, or certificates in dedicated configuration files or secrets management services. For instance, services like AWS Secrets Manager allow retrieval of secrets at runtime without exposing them as environment variables, reducing the risk of leakage through process listings or child process inheritance. Similarly, Microsoft's Secret Manager tool in ASP.NET Core provides a secure storage mechanism during development, ensuring secrets are not persisted in source code or environment spaces.[62] This approach aligns with broader security guidelines that prioritize ephemeral access to secrets over persistent environmental exposure.[53] In CI/CD pipelines, tools like GitHub Actions support encrypted secrets that are injected only at runtime, further limiting exposure.[63] For cases where environment variables are necessary, sanitization techniques are essential to prevent injection or manipulation vulnerabilities. Scripts should validate environment variable contents—such as checking for expected formats or lengths—before use, and always quote variables when expanding them to avoid word-splitting or globbing issues in shell commands. For example, in Bash, using double quotes around${VAR} ensures safe expansion even if the variable contains spaces or special characters.[64] Additionally, limit the scope of exported variables by declaring them locally within functions or scripts using the local keyword, preventing unintended propagation to subprocesses. The CERT Secure Coding Standard recommends clearing unnecessary environment variables with clearenv() or equivalent before invoking external programs to minimize the attack surface.
Specialized tools can further enhance isolation and management of environment variables. In application development, libraries like dotenv load variables from .env files at startup, keeping them separate from the global environment and allowing easy exclusion from version control via .gitignore. This facilitates environment-specific configurations without direct export to the shell. In containerized environments, Docker's --env-file option during docker run or in Compose files injects variables from a file into the container's namespace only, isolating them from the host system and supporting rotation without rebuilding images.[65] Docker best practices emphasize using such files for non-sensitive configs while reserving secrets for volume mounts or integrated managers to avoid exposure.[66]
Regular auditing is crucial for maintaining security. Inspect the environment periodically using commands like [env](/page/Env) | [grep](/page/Grep) -i sensitive to identify and review potentially exposed variables, integrating this into CI/CD pipelines or security scans.[67] Where modification risks exist, declare variables as read-only in Bash with the readonly builtin (e.g., readonly VAR=value), which prevents reassignment or unexport within the current shell session and its children. OWASP recommends combining these audits with automated scanning tools to detect hardcoded or leaked secrets across systems.[53]