Содержание
- Зачем редактировать переменные
- Способ 1: Свойства «Компьютера»
- Способ 2: «Командная строка»
- Вопросы и ответы
Переменная среды (окружения) в Виндовс хранит информацию о настройках ОС и пользовательских данных. Обозначается она с помощью парного символа «%», например:
%USERNAME%
С помощью этих переменных можно передавать необходимую информацию операционной системе. Например, %PATH% хранит список директорий, в которых Виндовс ищет исполняемые файлы, если путь к ним не задан явно. %TEMP% хранит временные файлы, а %APPDATA% — настройки программ пользователя.
Зачем редактировать переменные
Изменение переменных среды может помочь, если вы хотите перенести папку «Temp» или «AppData» в другое место. Редактирование %PATH% даст возможность запускать программы из «Командной строки», не указывая каждый раз длинный путь к файлу. Давайте рассмотрим методы, которые помогут в достижении этих целей.
Способ 1: Свойства «Компьютера»
В качестве примера программы, которую необходимо запустить, используем Skype. Попытавшись активировать это приложение из «Командной строки», вы получите такую ошибку:
Это происходит потому, что вы не задали полный путь к исполняемому файлу. В нашем случае полный путь выглядит вот так:
"C:Program Files (x86)SkypePhoneSkype.exe"
Чтобы это не повторять каждый раз, давайте добавим директорию Скайпа в переменную %PATH%.
- В меню «Пуск» нажмите правой кнопкой мыши на «Компьютер» и выберите «Свойства».
- Затем перейдите на «Дополнительные параметры системы».
- На вкладке «Дополнительно» нажмите на «Переменные среды».
- Откроется окно с различными переменными. Выберите «Path» и нажмите «Изменить».
- Теперь необходимо дописать путь к нашей директории.
Путь нужно указывать не к самому файлу, а к папке, в которой он находится. Обратите внимание, что разделителем между директориями является «;».
Дописываем путь:
C:Program Files (x86)SkypePhone
и жмем «ОК».
- Если есть необходимость, таким же образом вносим изменения в другие переменные и жмем «ОК».
- Завершаем сеанс пользователя, чтобы изменения сохранились в системе. Снова заходим в «Командную строку» и пытаемся запустить Скайп, введя
skype
Готово! Теперь вы можете запускать любую программу, а не только Skype, находясь в любой директории в «Командной строке».
Способ 2: «Командная строка»
Рассмотрим случай, когда мы хотим установить %APPDATA% на диск «D». Эта переменная отсутствует в «Переменных среды», поэтому ее невозможно изменить первым способом.
- Чтобы узнать текущее значение переменной, в «Командной строке» введите:
- Для того чтобы изменить ее значение, введите:
- Проверим текущее значение %APPDATA%, введя:
echo %APPDATA%
В нашем случае эта папка находится по адресу:
C:UsersНастяAppDataRoaming
SET APPDATA=D:APPDATA
Внимание! Убедитесь, что точно знаете зачем вы это делаете, поскольку необдуманные действия могут привести к неработоспособности Виндовс.
echo %APPDATA%
Значение успешно изменено.
Изменение значений переменных среды требует определенных знаний в этой сфере. Не играйтесь со значениями и не редактируйте их наугад, чтобы не навредить ОС. Хорошо изучите теоретический материал, и только после этого переходите к практике.
Еще статьи по данной теме:
Помогла ли Вам статья?
Любая операционная система нуждается в способе хранения различных настроек и прочей информации для нормальной работы. Для этого практически все операционные системы используют специальные переменные – переменные среды (environment variables).
Примечание! Переменная – это область памяти, хранящая те или иные данные, используемые программой.
В современных версиях Windows они бывают двух типов:
- пользовательские, хранящие параметры для конкретных пользователей;
- системные, хранящие параметры для всей системы.
Можно привести несколько примеров переменных сред:
- SystemDrive – обозначает диск системы (обычно это С:);
- SystemRoot – хранит папку системы (обычно это C:WINDOWS);
- PATH – обозначает «рабочие» папки, содержащие системные приложения.
Приложения, расположенные в папках указанных в PATH, можно вызывать без предварительного выбора каталога.
Зачем редактировать переменные?
Как правило, эти переменные не приходится редактировать вручную, поскольку они используются в параметрах, которые не нужно менять регулярно. Вручную редактировать эти данные приходится при ручной установке утилит и при устранении конфликтов между автоматически добавляемыми значениями.
Внимание! Некорректное изменение может привести к нарушению в работе тех или иных приложений или системы в целом.
Способы редактирования и создания
Переменные среды в Windows 7, 8, 10 можно легко редактировать самостоятельно. Это делается различными способами – через Свойства компьютера, с помощью командной строки и путем редактирования реестра.
Через Свойства компьютера
Проще всего отредактировать эти значения с помощью графического интерфейса. Для этого следует в Проводнике щелкнуть правой кнопкой мыши по иконке компьютера («Этот компьютер» в Windows 10, «Мой компьютер» в Windows 7) и выбрать «Свойства».
Далее следует открыть «Дополнительные параметры системы», а в появившемся окне «Свойства системы» — «Переменные среды».
После этого появится окно, позволяющее с помощью удобного графического интерфейса просматривать, добавлять, редактировать и удалять нужные элементы.
Интерфейс создания и изменения предельно прост – достаточно указать имя и значения. Предусмотрены диалоги для удобства выбора каталогов и файлов.
Через командную строку
Чтобы начать редактирование этим способом, необходимо открыть командную строку в режиме администратора. Для этого необходимо нажать Win+R, набрать в поле «cmd» и нажать Ctrl+Shift+Enter.
Для работы с переменными окружениями в командной строке Windows 7, 8, 10 предусмотрена утилита setx.
Для создания или изменения значения переменной среды пользователя данная утилита имеет следующий синтаксис:
setx new_var hello_world
Здесь new_var – название, a hello_world – значение.
Для создания или изменения системной переменной следует добавить параметр /M, например:
setx new_sys_var hello_eternity /M
Примечание! В случае, если название и/или значение содержат хотя бы один пробел, нужно использовать кавычки:
setx “new var” “hello_world”
Для очистки значения можно просто указать кавычки в качестве значения:
setx new_var “”
При этом утилита setx не может удалять переменные полностью. Это можно сделать путем «прямого» удаления соответствующей записи в реестре с помощью утилиты REG. Для пользовательской переменной команда будет выглядеть так:
REG delete HKCUEnvironment /F /V new_var
Для системной она будет такой:
REG delete "HKLMSYSTEMCurrentControlSetControlSession ManagerEnvironment" /F /V new_sys_var
Замечание по поводу кавычек актуально и для этих команд.
Через реестр
Для управления этими данными через реестр достаточно встроенного редактора regedit. Чтобы его открыть следует нажать Win+R, ввести в поле «regedit» и нажать OK. Для управления пользовательскими параметрами следует открыть ветку HKEY_CURRENT_USEREnvironment, для управления системными — HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment.
Как узнать список переменных сред
Иногда нужно просто узнать список этих значений. Для этого достаточно набрать set в командной строке. Также их можно сохранить в текстовом файле. Для этого необходимо перейти в папку сохранения файлов по своему усмотрению, например ввести в консоли:
cd %HOMEPATH%
Тут используется переменная среды HOMEPATH. Далее достаточно такой команды:
set > variables.txt
Тут можно изменить название файла на свое усмотрение, но расширение .txt лучше оставить.
Также эти данные можно экспортировать с помощью редактора реестра. Для этого необходимо открыть соответствующую ветку реестра указанную ранее и выбрать Файл – Экспорт. В поле «Тип файла» следует выбрать «Текстовые файлы (*.txt)». Далее можно выбрать нужную папку, ввести название и сохранить данные.
Внимание! Не рекомендуется таким образом архивировать переменные среды путем создание файла типа *.reg.
An environment variable is a dynamic-named 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 don’t 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.COM
or 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-deliminated (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.
It is conventional for environment variable names to be chosen to be in all upper case. In programming code generally, this helps to distinguish environment variables from other kinds of names in the code. On Unix-like operating systems, environment variable names are case sensitive, but they are not on DOS, OS/2, and Windows.
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:
If xyz
needed to be appended to the value of the HOME
variable, one might type:
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. 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:
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 # 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 "0 or more spaces"
shows the internal ones too. In CMD.EXE
, it is possible to assign local variables that do not leak outside using the SETLOCAL
command.
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{DeveloperNameAppName}
(Microsoft Windows): for storing application settings. Many applications incorrectly useUSERPROFILE
for application settings in Windows:USERPROFILE
should 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.,vt100
ordumb
).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
getpwuid
andgetuid
,$HOME
is 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.
$LIBPATH
or$SHLIB_PATH
- Alternatives to
$LD_LIBRARY_PATH
typically used on older Unix versions.
$LANG, $LC_ALL, $LC_...
$LANG
is 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_DATE
etc.).$LC_ALL
can 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 a Lynx) can be used. A
%s
token 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 /E
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 121[10] characters, therefore the variable is best not modified via theSET
command. 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.SYS
directiveMENUITEM
before launching the primary command processor. Its main purpose is to allow further special cases inAUTOEXEC.BAT
and similar batchjobs depending on the selected option at boot time. This can be emulated under DR-DOS by utilizing theCONFIG.SYS
directiveSET
likeSET 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.COM
still only supports a maximum of 126 characters at the prompt by default (unless overridden with/U:128..255
to 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..1024
to 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.COM
orC:DOSCOMMAND.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.SYS
directiveSHELL
), 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
/Y
switch (to assume «Yes» on queries) as the default for theCOPY
,XCOPY
, andMOVE
commands. A default of/Y
can be overridden by supplying the/-Y
switch on the command line. The/Y
switch 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
DIR
command, including file specifications. Preset default switches can be overridden by providing the negative switch on the command line. For example, if%DIRCMD%
contains the/W
switch, then it can be overridden by usingDIR /-W
at the command line. This is similar to the environment variable%$DIR%
under DOS Plus[19] and a facility to define default switches forDIR
through its/C
or/R
switches under DR-DOSCOMMAND.COM
.[11]%DIRCMD%
is also supported by the externalSDIR.COM
/DIR.COM
Stacker 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=ON
orSET NO_SEP=1
under 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
$PATH
variable (but some DOS and Windows applications also use the list to search for data files similar to$LD_LIBRARY_PATH
on Unix-like systems). It is usually changed via thePATH
(orPATH /E
under 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 theSET
command.[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 thePROMPT
command.
%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.COM
at the startup of secondary shells.[20]
%DRDOSCFG%
/%NWDOSCFG%
/%OPENDOSCFG%
- This variable contains the directory[21] (without trailing «
«) where to search for
.INI
and.CFG
configuration files (that is, DR-DOS application specific files likeTASKMGR.INI
,TASKMAX.INI
,VIEWMAX.INI
,FASTBACK.CFG
etc., class specific files likeCOLORS.INI
, or global files likeDRDOS.INI
,NWDOS.INI
,OPENDOS.INI
, orDOS.INI
), as used by theINSTALL
andSETUP
commands 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-DOSSYS
command under a foreign operating system.[22]
%DRSYS%
- Setting this variable to «
ON
» or «1
» will force some versions of the DR-DOSSYS
command to work under foreign operating systems instead of displaying a warning.[22]
%FBP_USER%
- Specifies the user name used by the FastBack command
FBX
and{user}.FB
configuration 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.COM
this variable defines the string displayed by the$I
token of thePROMPT
command.[20] It can be used, for example, to inform the user how to exit secondary shells.
%LOGINNAME%
- In some versions of DR-DOS
COMMAND.COM
this variable defines the user name displayed by the$U
token of thePROMPT
command, 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/Y
to automatically assume «Yes» on queries, thereby suppressing such prompts. If, however, the parameter/Y:yn
is used to specify the «Yes»/»No» characters (thereby overriding any%NOCHAR%
setting), queries are not suppressed. See also the relatedCONFIG.SYS
directiveNOCHAR
and 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-DOSINTERSVR
looks 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
$X
token of thePROMPT
command beforeCOMMAND.COM
displays 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.SYS
directiveSWITCHAR
(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.INI
to be used by the DR-DOSTASKMGR
multitasker 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
VER
command.[21] It is also used for the$V
token of thePROMPT
command 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/Y
to automatically assume «Yes» on queries, thereby suppressing such prompts. If, however, the parameter/Y:y
is used to specify the «Yes» character (thereby overriding any%YESCHAR%
setting), queries are not suppressed. See also the relatedCONFIG.SYS
directiveYESCHAR
and 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
CLS
command 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.SYS
console driver is detected, the DR-DOSCOMMAND.COM
will directly clear the screen viaINT 10h/AH=00h
BIOS function, like MS-DOS/PC DOSCOMMAND.COM
does. A specialnnn
-notation for octal numbers is supported to allow the definition of special characters like ESC (ASCII-27 = «←» = 1Bh = 33o), as f.e. inSET $CLS=33[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
/L
or/W
.[20][19] See also the similar environment variable%DIRCMD%
and theDIR
options/C
and/R
of 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/P
to 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
/P
option 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 /W
orTYPE 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=33[1m
with ANSI.SYS loaded orSET $ON=16
for an IBM or ESC/P printer. For the specialnnn
octal 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=33p
.[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=33[0m
with ANSI.SYS loaded orSET $OFF=24
for an IBM or ESC/P printer. For the specialnnn
octal 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=33q
.[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
TYPE
under 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=17
for an IBM or ESC/P printer. For the specialnnn
octal 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
TYPE
under DR-DOS 7.02 and higher. It is used to return to the normal output format, i.e.SET $FOOTER=2214
in the printer example above. For the specialnnn
octal 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]
forDIR
options/P
and/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]
System path variables[citation needed] refer to locations of critical operating system resources, and as such generally are not user-dependent.
%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.[26]
%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$PATH
variable.
%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).
%CommonProgramFiles%
- This variable points to the Common Files directory. The default is «
C:Program FilesCommon Files
» in the English version of Windows.
%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%[27] | Yes | C:Documents and SettingsAll Users | C:ProgramData[27] |
%APPDATA%[27] | Yes | C:Documents and Settings{username}Application Data | C:Users{username}AppDataRoaming[27] |
%CommonProgramFiles%[27] | Yes | C:Program FilesCommon Files | C:Program FilesCommon Files[27] |
%CommonProgramFiles(x86)%[27] | Yes | C:Program Files (x86)Common Files (only in 64-bit version) | C:Program Files (x86)Common Files (only in 64-bit version)[27] |
%CommonProgramW6432%[27] | Yes | %CommonProgramW6432% (not supported, not replaced by any value) | C:Program FilesCommon Files (only in 64-bit version)[27] |
%COMPUTERNAME% | No | {computername} | {computername} |
%ComSpec% | No | C:WindowsSystem32cmd.exe | C:WindowsSystem32cmd.exe |
%HOMEDRIVE%[27] | No | C: | C:[27] |
%HOMEPATH%[27] | Yes | Documents and Settings{username} | Users{username}[27] |
%LOCALAPPDATA%[27] | Yes | %LOCALAPPDATA% (not supported, not replaced by any value) | C:Users{username}AppDataLocal[27] |
%LOGONSERVER% | No | \{domain_logon_server} | \{domain_logon_server} |
%PATH% | Yes | C:Windowssystem32;C:Windows;C:WindowsSystem32Wbem;{plus program paths} | C:Windowssystem32;C:Windows;C:WindowsSystem32Wbem;{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%[27] | Yes | %ProgramData% (not supported, not replaced by any value) | %SystemDrive%ProgramData[27] |
%ProgramFiles%[27] | Yes | %SystemDrive%Program Files | %SystemDrive%Program Files[27] |
%ProgramFiles(x86)%[27] | Yes | %SystemDrive%Program Files (x86) (only in 64-bit version) | %SystemDrive%Program Files (x86) (only in 64-bit version)[27] |
%ProgramW6432%[27] | Yes | %ProgramW6432% (not supported, not replaced by any value) | %SystemDrive%Program Files (only in 64-bit version)[27] |
%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%system32WindowsPowerShellv1.0Modules | |
%PUBLIC%[27] | Yes | %PUBLIC% (not supported, not replaced by any value) | %SystemDrive%UsersPublic[27] |
%SystemDrive%[27] | No | C: | C:[27] |
%SystemRoot%[27] | No | The Windows directory, usually C:Windows, formerly C:WINNT | %SystemDrive%Windows[27] |
%TEMP%[27] and %TMP%[27] | Yes | %SystemDrive%Documents and Settings{username}Local SettingsTemp | %SystemRoot%TEMP (for system environment variables %TMP% and %TEMP%), %USERPROFILE%AppDataLocalTemp[27] (for user environment variables %TMP% and %TEMP%) |
%USERDOMAIN% | No | {userdomain} | {userdomain} |
%USERNAME% | No | {username} | {username} |
%USERPROFILE%[27] | Yes | %SystemDrive%Documents and Settings{username} | %SystemDrive%Users{username}[27] |
%windir%[27] | No | %SystemDrive%WINDOWS | %SystemDrive%Windows[27] |
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, 4NT, Take Command 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.COM
of DR-DOS 7.02 and higher, this pseudo-variable returns the last error level returned by an external program or theRETURN
command, f.e. «0
«..»255
«.[28][29] See also the identically named pseudo-variable%ERRORLEVEL%
under Windows and theIF ERRORLEVEL
conditional 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
«.[28][29] 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 ERRORLEVEL
command.
%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.COM
of DR-DOS 7.02 and higher, this pseudo-variable returns the current SwitChar setting of the system, either «/
» (DOS style) or «-
» (Unix style).[30][31] See also the relatedCONFIG.SYS
directive 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.COM
since DR-DOS 7.02. See also theCHCP
command.
%_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.COM
since 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.[31][32] This variable was originally introduced by 4DOS,[10] but also became available withCOMMAND.COM
since DR-DOS 7.02. See also theCONFIG.SYS
directiveCOUNTRY
.
%_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.COM
since 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.COM
since 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.COM
since 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.COM
since 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.COM
since 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.COM
since 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
CD
when called without arguments. While a long filename can be returned underCMD.EXE
depending on the current directory, the fact that the current directory will always be in 8.3 format underCOMMAND.COM
will cause it to return a short filename underCOMMAND.COM
, even whenCOMMAND
internally callsCMD
.
%CMDCMDLINE%
- This pseudo-variable expands to the original startup parameters of
CMD.EXE
, f.e. «C:Windowssystem32cmd.exe
«. Under Windows’COMMAND.COM
, this may return something like «C:Windowssystem32cmd.exe /c ...
» due to the fact thatCOMMAND.COM
callsCMD.EXE
internally.
%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).[28][33][29] External commands and some internal commands set error levels upon execution. See also the identically named pseudo-variable%ERRORLEVEL%
under DR-DOS and theIF ERRORLEVEL
command.
%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.[34]
See also[edit]
- Variable (computer science)
- List of Unix commands
- List of DOS commands
- Special folder
- Modules Environment
- PWB shell
- Windows Registry
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 vis INSTALL directive; MS-DOS doesn’t.
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. MPDOSTIP. Release 157 (in German) (3 ed.). Archived from the original on 2016-11-04. Retrieved 2014-08-06. (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 the
MPDOSTIP.ZIP
collection.) [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.TXT
file, which is part of theMPDOSTIP.ZIP
collection.) [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.
- ^ 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.
- ^ 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). Heise Verlag. 2014 (22): 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. MPDOSTIP (in German). 7: ERRORLEVEL abfragen. Archived from the original on 2017-08-23. Retrieved 2017-08-23. [5] [6] (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. Archived from the original on 2018-05-27. Retrieved 2017-05-27.
External links[edit]
environ(7)
: user environment – Linux Programmer’s Manual – Overview, Conventions and Miscellaneaenviron(7)
– FreeBSD Miscellaneous Information Manualenviron(7)
– Darwin and macOS Miscellaneous Information Manualenviron(5)
– Solaris 10 Standards, Environments and Macros Reference Manual- «Environment Variables Wiki». Archived from the original on 2019-04-27.
- User Environment Variables
- fix setx.exe not found bug
An environment variable is a dynamic-named 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 don’t 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.COM
or 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-deliminated (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.
It is conventional for environment variable names to be chosen to be in all upper case. In programming code generally, this helps to distinguish environment variables from other kinds of names in the code. On Unix-like operating systems, environment variable names are case sensitive, but they are not on DOS, OS/2, and Windows.
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:
If xyz
needed to be appended to the value of the HOME
variable, one might type:
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. 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:
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 # 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 "0 or more spaces"
shows the internal ones too. In CMD.EXE
, it is possible to assign local variables that do not leak outside using the SETLOCAL
command.
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{DeveloperNameAppName}
(Microsoft Windows): for storing application settings. Many applications incorrectly useUSERPROFILE
for application settings in Windows:USERPROFILE
should 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.,vt100
ordumb
).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
getpwuid
andgetuid
,$HOME
is 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.
$LIBPATH
or$SHLIB_PATH
- Alternatives to
$LD_LIBRARY_PATH
typically used on older Unix versions.
$LANG, $LC_ALL, $LC_...
$LANG
is 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_DATE
etc.).$LC_ALL
can 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 a Lynx) can be used. A
%s
token 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 /E
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 121[10] characters, therefore the variable is best not modified via theSET
command. 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.SYS
directiveMENUITEM
before launching the primary command processor. Its main purpose is to allow further special cases inAUTOEXEC.BAT
and similar batchjobs depending on the selected option at boot time. This can be emulated under DR-DOS by utilizing theCONFIG.SYS
directiveSET
likeSET 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.COM
still only supports a maximum of 126 characters at the prompt by default (unless overridden with/U:128..255
to 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..1024
to 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.COM
orC:DOSCOMMAND.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.SYS
directiveSHELL
), 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
/Y
switch (to assume «Yes» on queries) as the default for theCOPY
,XCOPY
, andMOVE
commands. A default of/Y
can be overridden by supplying the/-Y
switch on the command line. The/Y
switch 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
DIR
command, including file specifications. Preset default switches can be overridden by providing the negative switch on the command line. For example, if%DIRCMD%
contains the/W
switch, then it can be overridden by usingDIR /-W
at the command line. This is similar to the environment variable%$DIR%
under DOS Plus[19] and a facility to define default switches forDIR
through its/C
or/R
switches under DR-DOSCOMMAND.COM
.[11]%DIRCMD%
is also supported by the externalSDIR.COM
/DIR.COM
Stacker 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=ON
orSET NO_SEP=1
under 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
$PATH
variable (but some DOS and Windows applications also use the list to search for data files similar to$LD_LIBRARY_PATH
on Unix-like systems). It is usually changed via thePATH
(orPATH /E
under 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 theSET
command.[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 thePROMPT
command.
%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.COM
at the startup of secondary shells.[20]
%DRDOSCFG%
/%NWDOSCFG%
/%OPENDOSCFG%
- This variable contains the directory[21] (without trailing «
«) where to search for
.INI
and.CFG
configuration files (that is, DR-DOS application specific files likeTASKMGR.INI
,TASKMAX.INI
,VIEWMAX.INI
,FASTBACK.CFG
etc., class specific files likeCOLORS.INI
, or global files likeDRDOS.INI
,NWDOS.INI
,OPENDOS.INI
, orDOS.INI
), as used by theINSTALL
andSETUP
commands 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-DOSSYS
command under a foreign operating system.[22]
%DRSYS%
- Setting this variable to «
ON
» or «1
» will force some versions of the DR-DOSSYS
command to work under foreign operating systems instead of displaying a warning.[22]
%FBP_USER%
- Specifies the user name used by the FastBack command
FBX
and{user}.FB
configuration 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.COM
this variable defines the string displayed by the$I
token of thePROMPT
command.[20] It can be used, for example, to inform the user how to exit secondary shells.
%LOGINNAME%
- In some versions of DR-DOS
COMMAND.COM
this variable defines the user name displayed by the$U
token of thePROMPT
command, 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/Y
to automatically assume «Yes» on queries, thereby suppressing such prompts. If, however, the parameter/Y:yn
is used to specify the «Yes»/»No» characters (thereby overriding any%NOCHAR%
setting), queries are not suppressed. See also the relatedCONFIG.SYS
directiveNOCHAR
and 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-DOSINTERSVR
looks 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
$X
token of thePROMPT
command beforeCOMMAND.COM
displays 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.SYS
directiveSWITCHAR
(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.INI
to be used by the DR-DOSTASKMGR
multitasker 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
VER
command.[21] It is also used for the$V
token of thePROMPT
command 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/Y
to automatically assume «Yes» on queries, thereby suppressing such prompts. If, however, the parameter/Y:y
is used to specify the «Yes» character (thereby overriding any%YESCHAR%
setting), queries are not suppressed. See also the relatedCONFIG.SYS
directiveYESCHAR
and 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
CLS
command 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.SYS
console driver is detected, the DR-DOSCOMMAND.COM
will directly clear the screen viaINT 10h/AH=00h
BIOS function, like MS-DOS/PC DOSCOMMAND.COM
does. A specialnnn
-notation for octal numbers is supported to allow the definition of special characters like ESC (ASCII-27 = «←» = 1Bh = 33o), as f.e. inSET $CLS=33[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
/L
or/W
.[20][19] See also the similar environment variable%DIRCMD%
and theDIR
options/C
and/R
of 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/P
to 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
/P
option 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 /W
orTYPE 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=33[1m
with ANSI.SYS loaded orSET $ON=16
for an IBM or ESC/P printer. For the specialnnn
octal 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=33p
.[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=33[0m
with ANSI.SYS loaded orSET $OFF=24
for an IBM or ESC/P printer. For the specialnnn
octal 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=33q
.[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
TYPE
under 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=17
for an IBM or ESC/P printer. For the specialnnn
octal 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
TYPE
under DR-DOS 7.02 and higher. It is used to return to the normal output format, i.e.SET $FOOTER=2214
in the printer example above. For the specialnnn
octal 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]
forDIR
options/P
and/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]
System path variables[citation needed] refer to locations of critical operating system resources, and as such generally are not user-dependent.
%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.[26]
%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$PATH
variable.
%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).
%CommonProgramFiles%
- This variable points to the Common Files directory. The default is «
C:Program FilesCommon Files
» in the English version of Windows.
%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%[27] | Yes | C:Documents and SettingsAll Users | C:ProgramData[27] |
%APPDATA%[27] | Yes | C:Documents and Settings{username}Application Data | C:Users{username}AppDataRoaming[27] |
%CommonProgramFiles%[27] | Yes | C:Program FilesCommon Files | C:Program FilesCommon Files[27] |
%CommonProgramFiles(x86)%[27] | Yes | C:Program Files (x86)Common Files (only in 64-bit version) | C:Program Files (x86)Common Files (only in 64-bit version)[27] |
%CommonProgramW6432%[27] | Yes | %CommonProgramW6432% (not supported, not replaced by any value) | C:Program FilesCommon Files (only in 64-bit version)[27] |
%COMPUTERNAME% | No | {computername} | {computername} |
%ComSpec% | No | C:WindowsSystem32cmd.exe | C:WindowsSystem32cmd.exe |
%HOMEDRIVE%[27] | No | C: | C:[27] |
%HOMEPATH%[27] | Yes | Documents and Settings{username} | Users{username}[27] |
%LOCALAPPDATA%[27] | Yes | %LOCALAPPDATA% (not supported, not replaced by any value) | C:Users{username}AppDataLocal[27] |
%LOGONSERVER% | No | \{domain_logon_server} | \{domain_logon_server} |
%PATH% | Yes | C:Windowssystem32;C:Windows;C:WindowsSystem32Wbem;{plus program paths} | C:Windowssystem32;C:Windows;C:WindowsSystem32Wbem;{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%[27] | Yes | %ProgramData% (not supported, not replaced by any value) | %SystemDrive%ProgramData[27] |
%ProgramFiles%[27] | Yes | %SystemDrive%Program Files | %SystemDrive%Program Files[27] |
%ProgramFiles(x86)%[27] | Yes | %SystemDrive%Program Files (x86) (only in 64-bit version) | %SystemDrive%Program Files (x86) (only in 64-bit version)[27] |
%ProgramW6432%[27] | Yes | %ProgramW6432% (not supported, not replaced by any value) | %SystemDrive%Program Files (only in 64-bit version)[27] |
%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%system32WindowsPowerShellv1.0Modules | |
%PUBLIC%[27] | Yes | %PUBLIC% (not supported, not replaced by any value) | %SystemDrive%UsersPublic[27] |
%SystemDrive%[27] | No | C: | C:[27] |
%SystemRoot%[27] | No | The Windows directory, usually C:Windows, formerly C:WINNT | %SystemDrive%Windows[27] |
%TEMP%[27] and %TMP%[27] | Yes | %SystemDrive%Documents and Settings{username}Local SettingsTemp | %SystemRoot%TEMP (for system environment variables %TMP% and %TEMP%), %USERPROFILE%AppDataLocalTemp[27] (for user environment variables %TMP% and %TEMP%) |
%USERDOMAIN% | No | {userdomain} | {userdomain} |
%USERNAME% | No | {username} | {username} |
%USERPROFILE%[27] | Yes | %SystemDrive%Documents and Settings{username} | %SystemDrive%Users{username}[27] |
%windir%[27] | No | %SystemDrive%WINDOWS | %SystemDrive%Windows[27] |
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, 4NT, Take Command 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.COM
of DR-DOS 7.02 and higher, this pseudo-variable returns the last error level returned by an external program or theRETURN
command, f.e. «0
«..»255
«.[28][29] See also the identically named pseudo-variable%ERRORLEVEL%
under Windows and theIF ERRORLEVEL
conditional 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
«.[28][29] 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 ERRORLEVEL
command.
%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.COM
of DR-DOS 7.02 and higher, this pseudo-variable returns the current SwitChar setting of the system, either «/
» (DOS style) or «-
» (Unix style).[30][31] See also the relatedCONFIG.SYS
directive 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.COM
since DR-DOS 7.02. See also theCHCP
command.
%_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.COM
since 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.[31][32] This variable was originally introduced by 4DOS,[10] but also became available withCOMMAND.COM
since DR-DOS 7.02. See also theCONFIG.SYS
directiveCOUNTRY
.
%_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.COM
since 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.COM
since 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.COM
since 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.COM
since 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.COM
since 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.COM
since 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
CD
when called without arguments. While a long filename can be returned underCMD.EXE
depending on the current directory, the fact that the current directory will always be in 8.3 format underCOMMAND.COM
will cause it to return a short filename underCOMMAND.COM
, even whenCOMMAND
internally callsCMD
.
%CMDCMDLINE%
- This pseudo-variable expands to the original startup parameters of
CMD.EXE
, f.e. «C:Windowssystem32cmd.exe
«. Under Windows’COMMAND.COM
, this may return something like «C:Windowssystem32cmd.exe /c ...
» due to the fact thatCOMMAND.COM
callsCMD.EXE
internally.
%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).[28][33][29] External commands and some internal commands set error levels upon execution. See also the identically named pseudo-variable%ERRORLEVEL%
under DR-DOS and theIF ERRORLEVEL
command.
%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.[34]
See also[edit]
- Variable (computer science)
- List of Unix commands
- List of DOS commands
- Special folder
- Modules Environment
- PWB shell
- Windows Registry
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 vis INSTALL directive; MS-DOS doesn’t.
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. MPDOSTIP. Release 157 (in German) (3 ed.). Archived from the original on 2016-11-04. Retrieved 2014-08-06. (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 the
MPDOSTIP.ZIP
collection.) [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.TXT
file, which is part of theMPDOSTIP.ZIP
collection.) [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.
- ^ 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.
- ^ 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). Heise Verlag. 2014 (22): 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. MPDOSTIP (in German). 7: ERRORLEVEL abfragen. Archived from the original on 2017-08-23. Retrieved 2017-08-23. [5] [6] (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. Archived from the original on 2018-05-27. Retrieved 2017-05-27.
External links[edit]
environ(7)
: user environment – Linux Programmer’s Manual – Overview, Conventions and Miscellaneaenviron(7)
– FreeBSD Miscellaneous Information Manualenviron(7)
– Darwin and macOS Miscellaneous Information Manualenviron(5)
– Solaris 10 Standards, Environments and Macros Reference Manual- «Environment Variables Wiki». Archived from the original on 2019-04-27.
- User Environment Variables
- fix setx.exe not found bug
Хотите быстро открывать любые нужные Вам папки, запускать Командную строку из любой директории или создавать автоматические сценарии для перемещения файлов? Тогда Вам просто необходимо знать, что такое переменные среды!
Сегодняшняя статья, думаю, будет интересна, в первую очередь, продвинутым пользователям Windows. Хотя, в принципе, знать о предмете разговора не помешает никому. Речь идёт о такой сущности операционной системы как переменные средЫ (ударение на последнем слоге).
Исполняемой средой в Windows является оболочка Командной строки (CMD.EXE). Соответственно переменные эти будут работать в первую очередь в консоли. Однако, поскольку Командная строка поддерживается на уровне системы всеми штатными средствами Windows, переменные окружения будут также отлично работать, например, в Проводнике, в Планировщике заданий или в любых BAT-файлах. Это даёт широкий простор для их применения в сфере автоматизации рутинных процессов при работе с файлами.
Общие данные о переменных окружения
Переменные среды чаще всего разделяют на системные и локальные. Системные могут, в свою очередь, быть встроенными в Windows изначально (имеют наивысший приоритет) или добавлены различными установленными программами. Такие переменные доступны из любой учётной записи и хранятся в разделе реестра HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment.
Локальные переменные среды тоже могут создаваться программно, однако, часто их создают сами пользователи вручную. Такие переменные доступны только в рамках активной в данный момент учётной записи пользователя, а в реестре хранятся в ветках HKEY_CURRENT_USEREnvironment и HKEY_CURRENT_USERVolatile Environment.
Физически переменная окружения являет собой строковый или мультистроковый параметр реестра. Имя его одновременно является именем переменной, а значение, соответственно, её содержимым. В качестве содержимого может выступать любая текстовая информация, команды, пути к папкам или даже ссылки на другие переменные. В последнем случае имя переменной, на которую ссылаются, обрамляется с двух сторон символами «%»:
Кстати, вышеупомянутый способ обрамления имени переменной среды знаками процента используется для вызова её значения в окружении Windows. Например, если в Командной строке Вы хотите вывести текущую дату, Вы можете воспользоваться командой ECHO и переменной DATE в формате: «echo %date%» (без кавычек). Значения переменных можно произвольно комбинировать с любым текстом или значениями других переменных, при условии, что Вы их имена тоже заключите в конструкцию «%…%»:
Думаю, общее представление о том, что такое переменные среды у Вас уже есть, поэтому давайте углубимся в их изучение и рассмотрим более подробно.
Переменные среды Windows
Смотреть существующие переменные среды, как мы уже выяснили, можно в реестре. Однако, это не совсем удобно, поскольку они раскиданы по нескольким веткам. Гораздо проще ознакомиться с полным списком доступных переменных окружения через Командную строку. Для этого вызовите её (WIN+R – cmd – Enter) и введите команду SET без каких-либо дополнительных параметров:
Стоит сказать, что список здесь немного неполный, поскольку не содержит ряда встроенных системных переменных, вроде DATE, TIME, RANDOM и т.п. Начнём, пожалуй, с них.
Системные переменные среды
Переменная | Типичное значение | Назначение |
---|---|---|
APPDATA | C:Documents and Settings%UserName%Application Data или C:Users%UserName%AppDataRoaming (Windows 7 и выше) | Хранит путь к папке с данными установленных программ. |
CMDEXTVERSION | число | Выдаёт версию расширений обработчика команд (Command Processor Extensions). |
COMMONPROGRAMFILES | Обычно: %ProgramFiles%Common Files | Хранит путь к каталогу Common Files. |
COMMONPROGRAMFILES(x86) | Обычно: %ProgramFiles(x86)%Common Files | Хранит путь к 32-битной версии каталога Common Files в 64-битных системах. |
COMPUTERNAME | Текст | Хранит имя Вашего компьютера, используемое для идентификации в сетях. |
COMSPEC | C:Windowssystem32cmd.exe | Содержит путь к файлу запуска Командной строки. При вводе переменной в адресной строке Проводника запускает консоль из текущей папки. |
DATE | Текущая дата | Выдаёт полную текущую дату в формате, заданном в настройках Даты и времени. |
ERRORLEVEL | Число или 0 | Хранит числовой код ошибки произошедшей в последней использованной команде. При отсутствии ошибок выдаёт 0. |
HOMEDRIVE | C:, D:, E: или иные буквы | Выдаёт букву диска, на котором хранится профиль пользователя. |
HOMEPATH | Обычно: Users%USERNAME% | Выдаёт путь до каталога с профилем пользователя. |
HOMESHARE | Путь, если есть | Если задана, хранит путь до общей папки в каталоге с профилем пользователя. |
LOCALAPPDATA | Обычно: C:Users%UserName%AppDataLocal | Хранит путь до папки с локальными данными установленных программ. |
NUMBER_OF_PROCESSORS | Число | Отображает количество ядер процессора в системе. |
OS | Текст | Отображает название архитектуры Вашей версии Windows (чаще всего Windows_NT для систем старше Windows 2000). |
PATH | Ряд путей | Хранит (через точку с запятой) список путей к различным папкам с исполняемыми файлами системных и прочих приложений. |
PATHEXT | Расширения файлов (.COM; .EXE; .BAT и т.д.) | Хранит (через точку с запятой) список расширений файлов, которые воспринимаются системой как исполняемые. |
PROCESSOR_ARCHITECTURE | Текст | Выдаёт код архитектуры процессора, установленного в системе (например, AMD64). |
PROCESSOR_IDENTIFIER | Текст | Выдаёт код архитектуры процессора, а также ряд дополнительных сведений о нём (модельный ряд, версия модели и т.п.). |
PROCESSOR_LEVEL | Число | Выдаёт код уровня архитектуры процессора (модельный ряд). |
PROCESSOR_REVISION | Число | Выдаёт номер ревизии процессора. |
PROGRAMDATA | Обычно: C:ProgramData | Хранит путь до каталога с данными установленных программ. |
PROGRAMFILES | Обычно: C:Program Files | Хранит путь до каталога установки программ по умолчанию. |
PROGRAMFILES(x86) | Обычно: C:Program Files (x86) | Хранит путь до каталога установки 32-битных программ в 64-битной Windows по умолчанию. |
PUBLIC | Обычно: C:UsersPublic | Хранит путь до общего каталога системы (папка «Общие»). |
RANDOM | Число от 0 до 32767 | Выдаёт случайное число от 0 до 32767. |
SAFEBOOT_OPTION | Текст | Существует только в режиме Безопасной загрузки и хранит код текущего режима работы (например, в режиме загрузки «с поддержкой командной строки» – Minimal или «с поддержкой сетевых драйверов» – Network). |
SYSTEMDRIVE | C:, D:, E: или иные буквы | Хранит букву диска, на котором установлена система (обычно совпадает с %HOMEDRIVE%). |
TEMP и TMP | Обычно: C:Users%USERNAME%AppDataLocalTemp | Хранит путь к временной папке пользователя. Переменная является одновременно и системной и пользовательской для обеспечения доступа к папкам из-под других учётных записей. |
TIME | Текущее время | Выдаёт текущее время в формате: часы:минуты:секунды.миллисекунды. |
WINDIR | Обычно: C:Windows | Хранит путь до системного каталога Windows. |
Локальные переменные среды
Если системные переменные окружения доступны всегда по всей системе, то локальные работают только в рамках конкретной учётной записи пользователя. Их количество может быть значительным, а состав отличаться даже для разных пользователей одного и того же ПК. Однако, есть ряд переменных, которые обычно присутствуют везде.
Переменная | Типичное значение | Назначение |
---|---|---|
ALLUSERSPROFILE | Обычно: C:All Users (до Windows XP) или C:Program Data (Windows 7 и выше) | Хранит путь к папке с данными установленных программ. |
CD | Путь | Хранит путь к текущей активной директории, в которой исполняются команды. |
CLIENTNAME | Текст (если существует) | Если задана, хранит имя компьютера, заданное в настройках текущего пользователя. |
CMDCMDLINE | Текст | Выдаёт полную команду (с параметрами), которая была использована для последнего запуска Командной строки. |
LOGONSERVER | Текст | Хранит имя контроллера домена текущего пользователя. |
PROMPT | Обычно: $P$G | Выдаёт параметры командной строки для текущего интерпретатора. |
SESSIONNAME | Обычно: Console | Выдаёт название типа текущей сессии Командной строки. При запуске с локального ПК имеет значение «Console». При удалённом вызове – «RDP-Tcp#<номер сеанса>». |
USERDOMAIN | Текст | Хранит имя домена (компьютера), в котором работает пользователь. |
USERNAME | Текст | Хранит имя учётной записи активного пользователя. |
USERPROFILE | Обычно: C:Users%USERNAME% | Выдаёт путь до каталога с профилем пользователя. |
Создание и правка переменных среды
Как видим, переменных окружения уже изначально существует довольно много. Однако, это не значит, что Вы будете их использовать все и должны помнить наизусть. Более того, на практике Вам может недоставать каких-нибудь значений и Вы, возможно, захотите создать собственные переменные окружения. Благо, что в Windows для этого есть, как минимум, три штатных способа!
Создание переменных среды в Редакторе реестра
Как мы уже говорили, переменные среды хранятся в реестре Windows. Соответственно, там же мы их можем создавать и править. Это не самый правильный способ, но, тем не менее, такая возможность есть.
Чтобы создать, к примеру, локальную переменную окружения откройте Редактор реестра (WIN+R – regedit – Enter) и в ветке HKEY_CURRENT_USEREnvironment создайте новый параметр расширяемого строкового, строкового или мультистрокового типа с нужным именем и значением. К примеру, создадим переменную MYNAME со значением «Руслан»:
Чтобы переменная стала доступна в системе нужно либо перезагрузить Windows, либо только сам Проводник. Последнее можно довольно просто сделать при помощи Диспетчера задач (CTRL+SHIFT+ESC). Достаточно только найти процесс «Проводник» (или explorer.exe) и перезапустить его (либо, в более ранних версиях Windows, снять задачу и создать её заново):
После перезапуска оболочки Windows добавленная переменная будет доступна во всех системных компонентах. Проверить же доступность можно, как всегда, в Командной строке через команду ECHO (echo %myname%).
Создание переменных среды в Командной строке
Если Вы уже привыкли к работе в консоли Windows, то создавать переменные среды Вы сможете и прямо в ней. Для создания и правки переменных в Командной строке используется уже знакомая нам команда SET. Только, если для вывода списка переменных мы использовали её без каких-либо параметров, то теперь нам потребуется дополнить команду именем переменной и её значением. Например, создать переменную MYSURNAME со значением «Тертышный» можно так: SET MYSURNAME=Тертышный:
Проверить доступность переменной можно не только уже знакомой командой ECHO но и при помощи всё той же SET с указанием имени переменной: SET MYSURNAME. Если же Вы к предыдущей команде припишите знак «=», то получившаяся функция удалит переменную окружения с указанным именем, например: SET MYSURNAME= (удалит переменную MYSURNAME).
При создании переменной окружения прямо в реестре она там отображалась, но для доступа к ней требовался перезапуск среды. При создании же в консоли перезапуск не нужен. Новая переменная становится доступной сразу после объявления. Правда, она нигде не сохраняется на постоянной основе и использовать её можно только в текущем сеансе Командной строки.
Чтобы сохранить такую переменную в реестр Вам потребуется выполнить манипуляции с командой REG. Например, для сохранения переменной в виде локальной команда будет следующей: REG ADD HKCUEnvironment /v MYSURNAME /t REG_EXPAND_SZ /d Тертышный или REG ADD HKCUEnvironment /v MYSURNAME /t REG_EXPAND_SZ /d %MYSURNAME%:
Создание переменных среды через Свойства системы
Наиболее безопасным и удобным для простого пользователя, на мой взгляд, является работа с переменными среды через одноимённую оснастку. Чтобы получить к ней доступ вызовите «Свойства системы» (контекстное меню значка «Компьютер» – «Свойства»), перейдите на вкладку «Дополнительно» и нажмите кнопку «Переменные среды» в самом низу:
В открывшемся окне можно управлять некоторыми уже существующими системными и локальными переменными окружения, а также создавать новые. В принципе, здесь ничего сложного нет – всё весьма наглядно. Для создания новой переменной достаточно заполнить всего два поля с её именем и значением. Как и в случае с добавлением переменной через реестр, здесь также требуется перезапуск среды для полноценной работы.
Примеры использования переменных среды
Наконец-то мы разобрались (надеюсь :)) с принципами создания и изменения переменных среды и сейчас рассмотрим несколько практических примеров их применения. Скажу сразу, что применений Вы можете придумать сами большое множество. А, если Вы понимаете синтаксис BAT-файлов, то возможности перед Вами откроются весьма обширные.
Одной из самых полезных системных переменных окружения, на мой взгляд, является %COMSPEC%. Если взглянуть на её значение, то мы увидим, что она запускает Командную строку. Однако, если Вы введёте данную переменную в адресной строке открытой в данный момент папки, то консоль автоматически откроется из этой директории. Такой «фокус» очень удобен, если Вы работаете с консольными приложениями и не хотите каждый раз вводить вручную адрес папки с исполняемыми файлами:
Часто при работе с консолью требуется получить путь или имя рабочей папки. Чтобы не вводить его, опять же, вручную, намного удобнее воспользоваться системной переменной среды %CD%. Данная переменная, как мы знаем, хранит путь активной в данный момент директории.
Переменные, хранящие в своём значении пути, довольно удобно использовать для быстрого перехода к нужным папкам в том же Проводнике. Например, чтобы открыть директорию временных файлов пользователя достаточно ввести в адресную строку %TMP%, а для доступа к папке Windows – %WINDIR% и нажать Enter. Здесь можете создать и свои переменные, например, %DWNLD% для открытия папки загрузок, %DSK% для Рабочего стола и т.п.
Рассмотрим популярную практическую задачу, использующую вышеупомянутый тип переменных – очистка каталога с временными файлами. Как мы знаем, часто различные программы не «убирают» за собой «мусор». В результате этого директория временных файлов медленно но верно увеличивается в объёме. Если Вам хочется автоматизировать её очистку, создайте BAT-файл следующего содержания:
Первая команда удалит каталог временных файлов со всеми подпапками, не спрашивая Вашего подтверждения. Вторая же заново создаст его. Стоит, однако, заметить, что, если Вы запустите такой «батник» во время работы системы, то папка TEMP полностью может и не удалиться, поскольку в ней могут находится ресурсы, используемые активными программами. В принципе, это не смертельно, но консоль выдаст ошибки.
Если же хотите чтобы всё прошло безупречно, лучше запускать очистку при старте Windows, закинув BAT-файл в папку «Автозагрузка» (путь обычно: %APPDATA%MicrosoftWindowsStart MenuProgramsStartup). Таким образом очистка будет происходить автоматом при каждом запуске системы и не будет стопориться активными процессами, поскольку они ещё не запущены.
В ряде случаев полезной бывает и переменная %RANDOM%. По умолчанию она генерирует случайное число от 0 до 32767. Однако, диапазон можно ограничить приписав после переменной конструкцию » %% число», где «число» – максимальная нужная величина диапазона. Например, получить число от 0 до 10 можно так: «ECHO %RANDOM% %% 11» (в диапазоне всего 11 чисел, включая 0). Немного «заморочившись» можно даже написать простенькую игру «Угадай число» в виде следующего BAT-файла:
@echo off
SET /a GUESS=%RANDOM% %% 101
:begin
SET try=
SET /p «try=Ваше число: «
if «%try%»==»» goto begin
if %try% LSS %GUESS% (echo Загаданное число больше.& goto begin)
if %try% GTR %GUESS% (echo Загаданное число меньше.& goto begin)
if %try%==%GUESS% echo Вы угадали!& pause
Вышеприведённый код реализует игру на угадывание числа от 0 до 100, которое получается как раз из системной переменной окружения %RANDOM%. Для нормального отображения кириллицы набор команд нужно сохранить в виде BAT-файла с кодировкой OEM 866 или DOS (в разных Блокнотах она обозначена по-разному). Быстро запустить его на выполнение можно из любой папки при помощи вышеупомянутого способа с использованием переменной %COMSPEC% и ввода имени BAT-файла:
Выводы
Несмотря не то, что переменные среды в большинстве случаев используют лишь системные администраторы и программисты, они могут здорово пригодиться и простым пользователям! Зная всего несколько из них и умея создавать собственные, Вы без особых проблем сможете, как минимум, получать быстрый доступ к любым нужным папкам.
Если же Ваш интерес будет большим, нежели просто попробовать, что это такое, то Вы можете пойти дальше и писать уже собственные пакетные файлы, автоматизирующие процессы удаления, перемещения и создания файлов с нужными Вам данными. И, пускай Командная строка не так функциональна как, скажем, консоль Linux bash, в умелых руках она может творить буквально чудеса! Не верите? Попробуйте сами!
P.S. Разрешается свободно копировать и цитировать данную статью при условии указания открытой активной ссылки на источник и сохранения авторства Руслана Тертышного.
Обновлено 28.06.2022
Добрый день уважаемые читатели и гости блога, сегодня я с вами хочу обсудить вот такую тему, что такое переменные среды Windows, где их можно использовать, как в обычной практике пользователя, так и в практике системного администратора, я вам приведу несколько примеров. Как все это дело настраивается и изменяется под ваши нужны, на мой взгляд это фундаментальные знания, понимание которых вам лучше покажет принцип работы операционных систем семейства Windows.
Что такое переменные среды windows
Давайте разберемся в понятии, и так переменная окружения (environment variable) это специального рода ссылки уменьшенного размера, на определенные объекты операционной системы Windows, используемые разными программами для хранения информации и взаимодействия с ней. Можно провести аналогию с относительными ссылками на сайтах, где нет явного указания на протокол. Чаще всего это пути до конкретных директорий в ОС.
ИЛИ
Переменная среды — это динамический «объект» на компьютере, содержащий редактируемое значение, которое может использоваться одной или несколькими программами в Windows. Переменные среды помогают программам узнать, в какой каталог устанавливать файлы, где хранить временные файлы и где найти настройки профиля пользователя. Они помогают формировать среду, которую программы на вашем компьютере используют для запуска.
Где используют переменные среды Windows
Приведу несколько примеров:
- В скриптах > когда нужно например каждому пользователю сделать какую-то настройку, для примера положить на рабочий стол новую папку с документами. Так как для каждого пользователя путь до рабочего стола свой, вида C:UserslackyDesktop, а можно обратиться и по относительному пути за счет переменной %HOMEPATH%, если вы в проводнике введете %HOMEPATH%Desktop, то попадете на рабочий стол текущего пользователя.
- в групповой политике, для настройки пользовательских окружений, например перемещаемые профили.
- Оптимизация кода > если в коде очень часто используются одни и те же пути к файлам или папкам, а так же ключам реестра, вы можете легко назначить короткую переменную для дальнейшего использования. Ниже я вам приведу сводный список по переменным средам windows 10 и предыдущих версий, а так же покажу как их создавать и менять.
Все переменные среды Windows 10 и других версий в своем составе имеют специальный оператор %. Он необходим, чтобы операционная система могла обработать поисковый запрос. Простой пример вы ищите папку TEMP и не знаете, где она располагается, вводите %TEMP% и поиск будет на всех локальных дисках и разделах.
Переменные среды передают информацию о вашем сеансе входа в систему на ваш компьютер. Например, когда приложению необходимо определить, где по умолчанию сохранять файл данных, оно обычно вызывает переменную среды HOMEPATH. Вероятно, вы никогда не устанавливали переменную HOMEPATH самостоятельно, и тем не менее она существует, потому что большинство переменных сред управляются вашей операционной системой. Мастер установки, такой как платформа Nullsoft Scriptable Install System (NSIS) с открытым исходным кодом, обновляет переменные среды при установке нового приложения. Иногда, когда вы устанавливаете что-то за пределами предполагаемого набора инструментов вашей операционной системы, вам, возможно, придется самостоятельно управлять переменной среды. Или вы можете добавить переменную среды в соответствии со своими предпочтениями.
Список переменных сред windows 10
Приведенный глобальный список, в полной мере подойдет и для Windows 7 и для Windows 8.1, все проверено лично. Уверен, что данные знания, очень сильно вам помогут оптимизировать свою работу.
- %ALLUSERSPROFILE% > данная переменная отправит вас в папку C:ProgramData
- %windir% > это папка C:Windows
- %APPDATA% > вы попадается в скрытую папку C:UsersИмя_пользователяAppDataRoaming
- %CommonProgramFiles% > папка C:Program FilesCommon Files
- %CommonProgramFiles(x86)% > перекинет вас в C:Program Files (x86)Common Files
- %CommonProgramW6432% > перекинет вас C:Program FilesCommon Files
- %COMPUTERNAME% > Имя_компьютера, используется скриптах
- %ComSpec% > откроет командную строку Windows 10 C:Windowssystem32cmd.exe
- %HOMEDRIVE% > путь к диску C:
- %HOMEPATH% > эта переменная среды windows перекинет вас в папку пользователя UsersИмя_пользователя
- %LOCALAPPDATA% > эта переменная среды windows перекинет вас в папку C:UsersИмя_пользователяAppDataLocal
- %LOGONSERVER% > Имя_компьютера
- %NUMBER_OF_PROCESSORS% > Количество_процессоров
- %OS% > Windows_NT, так же используется в скриптах
- %Path% > C:Windowssystem32;C:Windows;C:WindowsSystem32Wbem;
- %PATHEXT% .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
- %PROCESSOR_ARCHITECTURE% > x86 или AMD64, архитектура Windows
- %PROCESSOR_IDENTIFIER% > Intel64 Family 6 Model 37 Stepping 5, GenuineIntel
- %PROCESSOR_LEVEL% > 6
- %PROCESSOR_REVISION% > 2505 (пример)
- %ProgramData% > папка C:ProgramData
- %ProgramFiles% > C:Program Files
- %ProgramFiles(x86)% > папка C:Program Files (x86)
- %ProgramW6432% > C:Program Files
- %PROMPT% > $P$G
- %PSModulePath% > C:Windowssystem32WindowsPowerShellv1.0Modules согласитесь очеь быстро
- %PUBLIC% > C:UsersPublic
- %SystemDrive% > диск C:
- %SystemRoot% > C:Windows
- %TEMP% > C:UsersИмя_пользователяAppDataLocalTemp (по умолчанию)
- %TMP% > C:UsersИмя_пользователяAppDataLocalTemp (по умолчанию)
- %USERDOMAIN% > Имя_компьютера
- %USERDOMAIN_ROAMINGPROFILE% > Имя_компьютера
- %USERNAME% > Имя_пользователя
- %USERPROFILE% > C:UsersИмя_пользователя
Как вывести список всех переменных Windows
В Windows 10 и других версиях, можно вывести список всех переменных сред Windows, для этого откройте командную строку от имени администратора и введите команду SET. В результате вы получите все переменные среды windows 10 по умолчанию для конкретной операционной системы.
Для удобства вы можете экспортировать весь этот список в текстовый файл, для этого введите:
Вот содержимое данного документы.
То же самое можно посмотреть и с помощью оболочки PowerShell, в которой нужно ввести:
Name Value
—- ——
ALLUSERSPROFILE C:ProgramData
APPDATA C:UsersАдминистраторAppDataRoaming
CommonProgramFiles C:Program FilesCommon Files
CommonProgramFiles(x86) C:Program Files (x86)Common Files
CommonProgramW6432 C:Program FilesCommon Files
COMPUTERNAME DC01
ComSpec C:Windowssystem32cmd.exe
FP_NO_HOST_CHECK NO
HOMEDRIVE C:
HOMEPATH UsersАдминистратор
LOCALAPPDATA C:UsersАдминистраторAppDataLocal
LOGONSERVER \DC01
NUMBER_OF_PROCESSORS 4
OS Windows_NT
Path C:Program Files (x86)Common FilesOracleJavajavapath;C:Windowssystem32;C:Windo…
PATHEXT .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.CPL
PROCESSOR_ARCHITECTURE AMD64
PROCESSOR_IDENTIFIER Intel64 Family 6 Model 44 Stepping 2, GenuineIntel
PROCESSOR_LEVEL 6
PROCESSOR_REVISION 2c02
ProgramData C:ProgramData
ProgramFiles C:Program Files
ProgramFiles(x86) C:Program Files (x86)
ProgramW6432 C:Program Files
PSModulePath C:UsersАдминистраторDocumentsWindowsPowerShell Modules;C:Program FilesWindowsPo…
PUBLIC C:UsersPublic
SESSIONNAME Console
SystemDrive C:
SystemRoot C:Windows
TEMP C:Users836D~1AppDataLocalTemp1
TMP C:Users836D~1AppDataLocalTemp1
USERDNSDOMAIN ROOT.PYATILISTNIK.ORG
USERDOMAIN ROOT
USERDOMAIN_ROAMINGPROFILE ROOT
USERNAME Администратор
USERPROFILE C:UsersАдминистратор
windir C:Windows
Еще одним методом посмотреть переменные операционной системы, выступает реестр Windows. Нажимаем WIN+R и вводим regedit. В открывшемся окне редактор реестра, перейдите в ветку:
Для просмотра переменных для компьютера
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment
Для просмотра переменных для пользователя
HKEY_CURRENT_USEREnvironment
Создаем переменные среды windows 10 (Графический метод)
ПО мимо уже имеющихся переменных Windows 10, вы можете создать и новые, это очень легко и не запрещается. Что от вас требуется, вам необходимо зайти в свойства системы. Тут несколько методов, если мы говорим про Windows 10, то можно сделать через правый клик по кнопке «Пуск», выбрав пункт система.
Универсальный метод, это зайти в свойства моего компьютера или нажать сочетание клавиш WIN+Pause Breake.
С окне свойства системы, вы должны перейти в пункт «Дополнительные параметры системы»
Далее пункт переменные среды.
И перед вами два вида переменных сред Windows:
- Временные переменные temp
- Системные переменные
И те и другие можно легко изменить или создать.
Для примера я создам новую системную переменную, назову ее SYSPREP и укажу путь до папки C:WindowsSystem32Sysprep
Проверяю, что все добавилось. И теперь вбив переменную %SYSPREP% у меня откроется C:WindowsSystem32Sysprep.
Как видите тут ничего сложного нет, благодаря вот таким вещам вы можете сильно упростить себе жизнь и экономить много времени.
Управление переменными средами Windows через PowerShell
Переменные среды в PowerShell — это особые типы переменных, которые предоставляют системе информацию о среде операционной системы. С помощью переменных среды вы можете просматривать и изменять переменные в реестре Windows, а также переменные, установленные для конкретного сеанса.
PowerShell есть функция, называемая провайдерами, которая создает один или несколько дисков, представляющих собой иерархические структуры, подобные файловой системе, которые позволяют пользователю управлять различными областями в Windows. Один из этих провайдеров предназначен для переменных среды под названием Environment.
В PowerShell переменные среды хранятся на Env:, доступном через поставщика среды PowerShell. Это не физический диск, а виртуальная файловая система.
Как вы можете видеть выше, у поставщика среды есть диск с именем Env. Этот диск предоставляет все переменные среды в системе Windows. Например, командлет Get-ChildItem можно использовать для перечисления всех переменных пользовательской среды в вашей системе.
Get-ChildItem -Path Env: или вот так Get-ChildItem Env: | out-host -paging
Как установить локальную переменную среды Windows
Когда вы создаете обычную переменную, она считается локальной, то есть она не определена вне оболочки, которая ее создала, как только вы закроете текущее окно PowerShell, ваша переменная исчезнет — это есть локальная переменная. Давайте создадим ее.
$env:SiteName = ‘pyatilistnik.org’
Чтобы изменить значение нужной переменной, просто повторите команду с нужным значением.
Чтобы добавить к текущему значению, еще одно, то используйте оператор += и разделите значение точкой с запятой (;)
$env:SiteName += ‘;pyatilistnik.info’
Но не забываем, что это временная переменная для текущего сеанса.
Как сделать постоянные переменные среды Windows для пользователя
Чтобы установить переменную среды Windows, которая будет доступна для всех процессов, запускаемых вашей учетной записью, используйте следующее:
[System.Environment]::SetEnvironmentVariable(‘siteName’,’pyatilistnik .org’,[System.EnvironmentVariableTarget]::User)
Как сделать постоянные переменные среды Windows для компьютера
Чтобы создать переменную среды, видимую для каждого процесса, работающего на машине:
[System.Environment]::SetEnvironmentVariable(‘siteName’,’pyatilistnik .org’,[System.EnvironmentVariableTarget]::Machine)
Тут PowerShell использует класс [System.Environment] с методом SetEnvironmentVariable для переменной среды.
Или такой вариант:
[System.Environment]::SetEnvironmentVariable(‘siteName’,’pyatilistnik .info’)
Как удалить переменную среды Windows
Чтобы удалить нужную переменную используйте вот такую конструкцию, в моем примере я удалю переменную siteName.
[Environment]::SetEnvironmentVariable(«siteName», «», «Machine»)
Как выгрузить переменные среды Windows в файл через PowerShell
Если вы хотите сохранить список текущих переменных сред Windows в текстовом файле, то введите команду:
dir Env: | FL | FT -AutoSize >> c:temp1.txt
На этом у меня все, если у вас остались вопросы, то пишите постараемся вместе в них разобраться.
Создание и управление переменными средами Windows через командную строку
Не будим списывать со счетов старую, добрую командную строку, так как она умеет так же работать с переменными Windows. Запустите ее от имени администратора.
- Создадим новую пользовательскую переменную MY-EMAIL, для этого пишем:
setx MY-EMAIL «microsoftexam@yandex.ru»
Не забываем перезапустить командную строку, иначе новую переменную вы не увидите.
- Создадим новую системную переменную MY-EMAIL, для этого пишем:
setx /m MY-EMAIL «microsoftexam@yandex.ru»
- Переименовывание пользовательской и системной переменной среды
Просто повторите те же команды, что и выше, но с уже нужными, новыми значениями
- Добавляем еще одно значение в существующую пользовательскую переменную Windows, тут все добавляется через знак «;«.
setx MYWEBPC «microsoftexam@yandex.ru;microsoftexam2022@yandex.ru»
- Добавляем еще одно значение в существующую системную переменную Windows, тут все добавляется через знак «;«.
setx /m MY-EMAIL «microsoftexam@yandex.ru;microsoftexam2022@yandex.ru»
- Удаляем значение у пользовательской переменной MY-EMAIL
- Удаляем значение у системной переменной MY-EMAIL
- Удаляем переменную MY-EMAIL
REG delete «HKCUEnvironment» /F /V «MY-EMAIL»
REG delete «HKLMSYSTEMCurrentControlSetControlSession ManagerEnvironment» /F /V «MY-EMAIL»