Для быстрого доступа к командам в командной строке без необходимости ввода полного пути к исполняемому файлу можно добавить путь к папке с этими исполняемыми файлами в переменную PATH в Windows, особенно это может быть полезным при работе с adb, pip и python, git, java и другими средствами разработки с отладки.
В этой пошаговой инструкции о том, как добавить нужный путь в системную переменную PATH в Windows 11, Windows 10 или другой версии системы: во всех актуальных версиях ОС действия будут одинаковыми, а сделать это можно как в графическом интерфейсе, так и в командной строке или PowerShell. Отдельная инструкция про переменные среды в целом: Переменные среды Windows 11 и Windows 10.
Добавление пути в PATH в Свойствах системы
Для возможности запуска команд простым обращением к исполняемому файлу без указания пути, чтобы это не вызывало ошибок вида «Не является внутренней или внешней командой, исполняемой программой или пакетным файлом», необходимо добавить путь к этому файлу в переменную среды PATH.
Шаги будут следующими:
- Нажмите клавиши Win+R на клавиатуре (в Windows 11 и Windows 10 можно нажать правой кнопкой мыши по кнопке Пуск и выбрать пункт «Выполнить»), введите sysdm.cpl в окно «Выполнить» и нажмите Enter.
- Перейдите на вкладку «Дополнительно» и нажмите кнопку «Переменные среды».
- Вы увидите список переменных среды пользователя (вверху) и системных переменных (внизу). PATH присутствует в обоих расположениях.
- Если вы хотите добавить свой путь в PATH только для текущего пользователя, выберите «Path» в верхней части и нажмите «Изменить» (или дважды нажмите по переменной PATH в списке). Если для всех пользователей — то же самое в нижней части.
- Для добавления нового пути нажмите «Создать», а затем впишите новый путь, который требуется добавить в переменную PATH в новой строке. Вместо нажатия «Создать» можно дважды кликнуть по новой строке для ввода нового пути.
- После ввода всех необходимых путей нажмите «Ок» — ваша папка или папки добавлены в переменную PATH.
Внимание: после добавления пути в переменную PATH потребуется перезапустить командную строку (если она была запущена в момент изменения), чтобы использовать команды без указания полного пути.
Как добавить путь в переменную PATH в командной строке и PowerShell
Вы можете добавить переменную PATH для текущей сессии в консоли: то есть она будет работать до следующего запуска командной строки. Для этого используйте команду:
set PATH=%PATH%;C:\ваш\путь
Есть возможность добавить путь в PATH с помощью командной строки и на постоянной основе (внимание: есть отзывы, что может повредить записи в переменной PATH, а сами изменения производятся для системной переменной PATH), команда будет следующей:
setx /M path "%path%;C:\ваш\путь"
Набор команд для добавления пути в переменную PATH пользователя с помощью PowerShell:
$PATH = [Environment]::GetEnvironmentVariable("PATH") $my_path = "C:\ваш\путь" [Environment]::SetEnvironmentVariable("PATH", "$PATH;$my_path", "User")
Если требуется добавить путь в системную переменную PATH для всех пользователей, последнюю команду изменяем на:
[Environment]::SetEnvironmentVariable("PATH", "$PATH;$my_path", "Machine")
PATH
is an environment variable that specifies a set of directories, separated with semicolons (;
), where executable programs are located.
In this note i am showing how to print the contents of Windows PATH
environment variable from the Windows command prompt.
I am also showing how to add a directory to Windows PATH
permanently or for the current session only.
Cool Tip: List environment variables in Windows! Read More →
Print the contents of the Windows PATH
variable from cmd
:
C:\> path
– or –
C:\> echo %PATH%
The above commands return all directories in Windows PATH
environment variable on a single line separated with semicolons (;
) that is not very readable.
To print each entry of Windows PATH
variable on a new line, execute:
C:\> echo %PATH:;=&echo.%
- sample output -
C:\WINDOWS\system32
C:\WINDOWS
C:\WINDOWS\System32\Wbem
C:\WINDOWS\System32\WindowsPowerShell\v1.0\
C:\WINDOWS\System32\OpenSSH\
C:\Program Files\Intel\WiFi\bin\
C:\Program Files\Common Files\Intel\WirelessCommon\
C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL
C:\Program Files\Intel\Intel(R) Management Engine Components\DAL
C:\Program Files\Microsoft VS Code\bin
C:\Users\Admin\AppData\Local\Microsoft\WindowsApps
Cool Tip: Set environment variables in Windows! Read More →
Add To Windows PATH
Warning! This solution may be destructive as Windows truncates PATH
to 1024 characters. Make a backup of PATH
before any modifications.
Save the contents of the Windows PATH
environment variable to C:\path-backup.txt
file:
C:\> echo %PATH% > C:\path-backup.txt
Set Windows PATH For The Current Session
Set Windows PATH
variable for the current session:
C:\> set PATH="%PATH%;C:\path\to\directory\"
Set Windows PATH Permanently
Run as Administrator: The setx
command is only available starting from Windows 7 and requires elevated command prompt.
Permanently add a directory to the user PATH
variable:
C:\> setx path "%PATH%;C:\path\to\directory\"
Permanently add a directory to the system PATH
variable (for all users):
C:\> setx /M path "%PATH%;C:\path\to\directory\"
Info: To see the changes after running setx
– open a new command prompt.
Was it useful? Share this post with the world!
Sometimes we need to tell Windows where to look for a particular executable file or script. Windows provides a means to do this through the Path Environment Variable. The Path Environment Variable essentially provides the OS with a list of directories to look in for a particular .exe or file when the simple name of the file is entered at the command prompt.
For example, the Notepad.exe application resides in the C:\Windows\system32 directory. However, if we wish to open the Notepad application via the Windows Command Line, we need only type:
Opening Notepad.exe From the Windows Command Line:
C:\Users\John> notepad
This works because the Path variable on Windows by default contains a list of directories where application files and scripts are likely to be located. Each directory in the list is separated by a semi-colon.
Similarly, there is another environment variable, PATHEXT which specifies a list of file extensions which might be found when searching for the proper file within the paths in the Path variable. This is why we are able to type simply “Notepad” at the command prompt, instead of Notepad.exe.
Windows will first search the current directory (where the command prompt is a the time the command is executed) to find a name matching the one typed into the terminal, and then search the directories in the Path variable in order, beginning with the most likely locations, and continue until either a matching file name is located, or else return the “… is not recognized blah blah” message at the terminal.
Once a file with a matching name is located, Windows attempts to match the file extension (if one is present), again in the order specified in the PATHEXT variable. If a match is found, the file is processed accordingly.
There are both User-specific and machine-level PATH variables. Machine Path variables are available globally across the machine, and can only be modified by administrators. User Environment variables can be modified by both administrators, and the user with which the current profile is associated.
Adding a Directory to the User Path Variable from the Command Line
Any user can modify their own PATH variable from the Command Line (unless they have been specifically denied this ability by an administrator).
For example, when we wish to use SQLite from the Windows Command Line, we download the SQLite binaries, and place them in the directory of choice. However, in order to use the SQLite Command Line application without either navigating directly to the folder in which we placed it, or entering the full file path into our Windows Command Line, we need to add the directory containing the SQLite.exe to our User or System PATH environment variable.
Let’s say a user has downloaded the sqlite3.dll and sqlite3.exe binaries and located them in the directory C:\SQLite.
Now, in order to invoke the sqlite3.exe from the command line, we need to add the C:\SQLite directory to our PATH environment variable. We can do this from the command line by using the setx command:
The setx Command – Syntax:
C:\Users\John> setx "%path%;C:\SQLite"
When we modify environment variables using setx, the changes are not available in the current Console session – in other words, in order to see our changes, we need to exit, and open a new Console window. Then, we can use the following technique:
We can examine the contents of the PATH variable by typing:
Output PATH Variable to the Console:
C:\Users\John> echo %PATH%
Which gives the output:
Results of Echo %PATH% Command:
C:\Users\John>echo %PATH% C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\Wind owsPowerShell\v1.0\;C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\;C:\Program Files\Microsoft SQL Server\110\Tools\Binn\;C:\Program Files\ Microsoft SQL Server\110\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\1 10\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\Manage mentStudio\;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\Priv ateAssemblies\;C:\Program Files (x86)\Microsoft SQL Server\110\DTS\Binn\;C:\Prog ram Files (x86)\Common Files\Acronis\SnapAPI\;C:\Program Files (x86)\Windows Liv e\Shared;C:\Program Files\Calibre2\;C:\Program Files\Microsoft\Web Platform Inst aller\;C:\Users\John\AppData\Roaming\npm;C:\Program Files (x86)\nodejs\;C:\Progr am Files (x86)\Microsoft SDKs\Windows Azure\CLI\wbin;C:\Program Files (x86)\GtkS harp\2.12\bin;C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0\;C:\SQLite
We can see here that C:\SQLite has now been added to the paths available to the current user.
Adding a Directory to the System Path Variable from the Command Line
In the previous section, we used the setx command to add a directory to the current user’s Path variable. Sometimes, we want to make variables available at the system, or machine level. In that case, we use the same setx
command in conjunction with the /m flag. However, we need to run the Command Terminal as Administrator for this to work:
Add a Directory the the System PATH Variable Using the /m Flag:
C:\Users\John> setx /m path "%path%;C:\SQLite"
Adding a Directory to the Path Variable from the GUI
Or, we can do this using the GUI by navigating to Control Panel => All Control Panel Items => System, and then selecting the “Advanced System Settings” link:
Locate Advanced System Settings in Control Panels:
Then locate the “Environment Variables” button:
Open Environment Variables:
Opening Environment Variables, we see the following:
Editing Environment Variables:
Notice in the image above, there are two sections, User Variables for<Current User>, and System Variables.
Also note, there is not currently a Path variable for me, the current user. We will need to add one, and then add our new path to it:
Adding a User Path Variable in the Windows GUI:
Once we hit OK, We see we have the single item added to our user path variable.
Added Path Variable to User Environment Variables:
For some reason, this works differently than when we do this from the Command Line, when we use the setx
command from the terminal, the entirety of the system path variable is copied into the user path variable, including the new entry.
If we have Administrator permissions on our machine, we can do the same for the System PATH variable if we so choose.
Removing Directories from the PATH Variable
In some cases, we may need to remove a directory from our PATH variable. In these cases it is recommended to use the GUI, or edit the registry. It’s easiest to simply open the GUI, copy the contents of the PATH variable (either the User Path or the System Path) to a text editor, and remove the entries you want to delete. Then paste the remaining text back into the Edit Path window, and save.
Additional Resources and Items of Interest
- Installing and Using SQLite on Windows
- Getting Started with Git for the Windows Developer (Part I)
- Basic Git Command Line Reference for Windows Users
- Git: Interactively Stage Portions of a Single Changed File for Commit Using git add -p
Если Вам нужно настроить PATH в Linux — перейдите
сюда
↓
Contents
↓
Для чего используется |
|
Пример |
|
Добавить директорию в PATH |
|
Изучить содержимое PATH |
|
Errors |
|
Postgesql |
Для чего используется
Когда Вы выполняете какую-либо команду в консоли, система ищет соответствие
между названием этой команды и программой, которую можно выполнить.
Искать по всему жёсткому диску было бы слишком долго, поэтому поиск
осуществляется только по некоторым директориям.
Список этих особых директорий хранится в системной переменной PATH.
Пример
Предположим, что возникла необходимость запускать какую-то программу, например
Firefox
, непосредственно из командной строки.
Без предварительной подготовки ввод Firefox в консоль выдаст ошибку.
C:\Users\a>firefox
‘firefox’ is not recognized as an internal or external command, operable program or batch file.
To решить эту проблему нужно добавить директорию с испоняемым файлом firefox в PATH
Добавить директорию в PATH
Быстрый способ перейти к редактированию PATH — нажать клавишу Win и ввести в поиск env
Пошаговый способ:
Правый клик на Этот Компьютер (This PC) → Свойства (Properties)
Дополнительные параметры системы (Advanced system settings)
Дополнительно (Advanced) → Переменные среды (Environment Variables)
Если хотите менять для всей системы, то в окошке «Переменные среды»
(System Variables)
найдите строку PATH в блоке
«Системные переменные» (System variables)
выделите кликом и нажмите кнопку «Изменить…» (Edit…)
Если хотите менять только для своего пользователя, то делайте это в блоке
«Переменные среды пользователя %USERNAME%» (User variables for %USERNAME%)
Создайте новый путь (New)
Введите адрес директории в которой лежит нужная программа. В нашем случае это
C:\Program Files (x86)\Mozilla Firefox
Перезапустите консоль или открываем новую и пишем там firefox.
C:\Users\a>firefox
Браузер должен запуститься.
Изучить содержимое PATH
В PowerShell достаточно выполнить
echo $Env:Path
C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;
Или
Get-ChildItem Env:Path
Name Value
—- ——
Path C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPo…
В cmd.exe посмотреть список переменных
окружения можно выполнив команду
set
без параметров.
set
Выдача содержит системные переменные и переменные пользователя
а также дополнительную информацию. Содержимое PATH выделено зелёным.
Errors
-bash: syntax error near unexpected token `(‘
Скорее всего Вы пытаетесь добавить в unix PATH адрес из Windows, c пробелами, скобками и так далее.
Например:
andrey@olegovich-10:/usr/share$ export PATH=/mnt/c/Program Files (x86)/Common Files/Oracle/Java/javapath_target_1128437:$PATH
-bash: syntax error near unexpected token `(‘
Для решения этой проблемы Вам нужно экранировать пробелы и скобки. Если импортируется много путей и ввод очень длинный —
немного проще записать PATH=$PATH:/путь , если Вам подходит запись в конец.
Также нужно помнить, что все лишние пробелы сломают импорт — для проверки можно сделать весь скрипт в одну строку
в текстовом редакторе.
Также стоит помнить, что если Вы работаете в
bash под Windows
,
то переменные окружения нужно задавать через Windows.
andrey@olegovich-10:/usr/share$ export PATH=$PATH:/mnt/c/Program\ Files\ \(x86\)/Common\ Files/Oracle/Java/javapath_target_1128437
Postgesql
Приведу пример для использования psql из
bash под Windows
— это может пригодиться если Вы хотите временно добавить
путь к psql в PATH чтобы запустить
Postrgres
скрипт.
В моём случае psql.exe находится в папке C:\Program Files\PostgreSQL\12\bin
PATH=$PATH:/mnt/c/Program\ Files/PostgreSQL/12/bin
Related Articles:
Users can run an executable from windows command prompt either by giving the absolute path of the file or just by the executable file name. In the latter case, Windows searches for the executable in a list of folders which is configured in environment variables. These environment variables are as below.
1. System path
2. User path
The values of these variables can be checked in system properties( Run sysdm.cpl from Run or computer properties). Initially user specific path environment variable will be empty. Users can add paths of the directories having executables to this variable. Administrators can modify the system path environment variable also.
How to set path from command line?
In Vista, Windows 7 and Windows 8 we can set path from command line using ‘setx’ command.
setx path "%path%;c:\directoryPath"
For example, to add c:\dir1\dir2 to the path variable, we can run the below command.
setx path "%path%;c:\dir1\dir2"
Alternative way is to use Windows resource kit tools ‘pathman.exe‘. Using this command we can even remove a directory from path variable. See download windows resource kit tools. This works for Windows 7 also.
Add directory to system path environment variable:
Open administrator command prompt
Run the below command
pathman /as directoryPath
Remove path from system path environment variable:
Run the below command from elevated command prompt
pathman /rs directoryPath
Setting user path environment variable
For user environment varlables, admin privileges are not required. We can run the below command to add a directory to user path environment variable.
pathman /au directoryPath
To remove a directory from user path, you can run the below command.
pathman /ru directoryPath
Default option is not allowed more than ‘2’ time(s)
You get this error if you have not enclosed ‘path’ in double quotes. See the below example for setting the path of firefox.
C:\Users\>setx path %path%;"c:\Program Files (x86)\Mozilla Firefox\" ERROR: Invalid syntax. Default option is not allowed more than '2' time(s). Type "SETX /?" for usage.
Now if you move %path% to be in the double quotes
C:\Users\>setx path "%path%;c:\Program Files (x86)\Mozilla Firefox\" SUCCESS: Specified value was saved. C:\Users\>