- Как отредактировать PATH в Windows 7, 8 и Windows 10?
- Что такое PATH система Windows?
- Как добавить папку в PATH?
- Path в операционной системе Windows 7 и Windows 8
- Path в операционной системе Windows 10
- Системная переменная окружения PATH в Windows
- Для чего используется
- Пример
- Добавить директорию в PATH
- Изучить содержимое PATH
- Ошибки
- -bash: syntax error near unexpected token `(‘
- Postgesql
- Похожие статьи:
- Adding a Location to the Windows Path
- Set PATH and other environment variables in Windows 10
- Set environment variables from command prompt
- Set environment variable by Registry edit
Как отредактировать PATH в Windows 7, 8 и Windows 10?
Как запустить программу из командной строки не переходя каждый раз в папку с программой?! Как запускать сторонние программы так, как, например, программу IPCONFIG, которая не требует перехода в папку?
Что такое PATH система Windows?
Если вы скачали программу командной строки, например ADB (Android Debuggin Bridge), то вы не сможете запустить ее просто вписав adb в командной строке, как вы всегда поступали с системными командами Windows (IPCONFIG, NETSTAT и т.п.). Вместо этого вы должны будете указать командную строку содержащую полный путь к exe-файлу.
Это достаточно сложно писать в командной строке без ошибок, тем более, если вам приходится делать это достаточно часто.
PATH система Windows сообщает вашей операционной системе каталоги, в которых следует искать исполняемые файлы. Например ранее упоминаемая программа ipconfig.exe расположена в каталоге C:\Windows\System32, который в свою очередь уже добавлен в PATH Windows. При вводе команды ipconfig система обыщет все папки из PATH на наличие файла ipconfig.exe и запустит его выполнение.
Если вы хотите то же удобство с программой (в нашем примере это ADB), то приложение ADB необходимо добавить в PATH Windows и после этого для запуска достаточно будет вписать в командную строку:
Больше ничего впечатывать не придется.
Как добавить папку в PATH?
В Windows 7, 8 и Windows 10 попасть в настройки PATH можно так: Панель управления / Система / Дополнительные переменные среды.
Далее перейти в «Переменные среды».
В окне «Переменные среды» обратите внимание на переменную с именем Path. Выберите ее и нажмите «Изменить..»
Дальнейшие действия одинаковы в Windows 7 и 8, но иные, облегченные, в Windows 10.
Path в операционной системе Windows 7 и Windows 8
В этих системах переменная Path является не более, чем длинной строкой текста с адресами каталогов системы. В этот текст мы добавим каталог и с нашей программой ADB.
Для того, чтобы добавить запись с путем к исполняемому файлу в Windows 7 и 8 к тексту нужно добавить путь, которому предшествует точка с запятой, разделяющая различные записи. Например так:
Добавлять такой путь в текст path нужно только в конец строки.
После ввода нажмите ОК. Все, мы добавили каталог в patch Windows 7 и 8.
Path в операционной системе Windows 10
В операционной системе Windows 10 этот процесс проще и менее запутанный. После нажатия кнопки «Изменить…» откроется новое диалоговое окно с расположенными в отдельных строках путях path.
Это улучшение позволяет проще и нагляднее видеть имеющиеся пути path и облегчает добавить новые пути.
Для добавления нового пути в переменную path Windows 10 нужно нажать «Новый», добавить путь C:\Android\platform-tools и нажать ОК.
Новая запись появится в низу списка.
Теперь запуск Android Debug Bridge доступен из любого раздела командной строкой без ввода полного пути к исполняемому файлу.
Системная переменная окружения PATH в Windows
Если Вам нужно настроить PATH в Linux — перейдите сюда
Для чего используется | |
Пример | |
Добавить директорию в PATH | |
Изучить содержимое PATH | |
Ошибки | |
Postgesql |
Для чего используется
Когда Вы выполняете какую-либо команду в консоли, система ищет соответствие между названием этой команды и программой, которую можно выполнить.
Искать по всему жёсткому диску было бы слишком долго, поэтому поиск осуществляется только по некоторым директориям.
Список этих особых директорий хранится в системной переменной PATH.
Пример
Предположим, что возникла необходимость запускать какую-то программу, например Firefox , непосредственно из командной строки.
Без предварительной подготовки ввод Firefox в консоль выдаст ошибку.
‘firefox’ is not recognized as an internal or external command, operable program or batch file.
Чтобы решить эту проблему нужно добавить директорию с испоняемым файлом 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.
Браузер должен запуститься.
Изучить содержимое PATH
В PowerShell достаточно выполнить
Name Value —- —— Path C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPo.
В cmd.exe посмотреть список переменных окружения можно выполнив команду set без параметров.
Выдача содержит системные переменные и переменные пользователя а также дополнительную информацию. Содержимое PATH выделено зелёным.
Ошибки
-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
Похожие статьи:
Если остались вопросы — смело задавайте их в Telegram группе — aofeedchat либо воспользуйтесь поиском по сайту
Чтобы следить за выходом новых статей — подписывайтесь на Telegram канал aofeed
Adding a Location to the Windows Path
A number of my books tell the reader to perform tasks at the command line. What this means is that the reader must have access to applications stored on the hard drive. Windows doesn’t track the location of every application. Instead, it relies on the Path environment variable to provide the potential locations of applications. If the application the reader needs doesn’t appear on the path, Windows won’t be able to find it. Windows will simply display an error message. So, it’s important that any applications you need to access for my books appear on the path if you need to access them from the command line.
You can always see the current path by typing Path at the command line and pressing Enter. What you’ll see is a listing of locations, each of which is separated by a semicolon as shown here (your path will differ from mine).
In this case, Windows will begin looking for an application in the current folder. If it doesn’t find the application there, then it will look in C:\Python33\ , then in C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common , and so on down the list. Each potential location is separated from other locations using a semicolon as shown in the figure.
There are a number of ways to add a location to the Windows path. If you only need to add a path temporarily, you can simply extend the path by setting it to the new value, plus the old value. For example, if you want to add C:\MyApp to the path, you’d type Path=C:\MyApp;%Path% and press Enter. Notice that you must add a semicolon after C:\MyApp . Using %Path% appends the existing path after C:\MyApp . Here is how the result looks on screen.
Of course, there are times when you want to make the addition to the path permanent because you plan to access the associated application regularly. In this case, you must perform the task within Windows itself. The following steps tell you how.
- Right click Computer and choose Properties from the context menu or select System in the Control Panel. You see the System window shown here open.
- Click Advanced System Settings. You see the Advanced tab of the System Properties dialog box shown here.
- Click Environment Variables. You see the Environment Variables dialog box shown here. Notice that there are actually two sets of variables. The top set affects only the current user. So, if you plan to use the application, but don’t plan for others to use it, you’d make the Path environment variable change in the top field. The bottom set affects everyone who uses the computer. This is where you’d change the path if you want everyone to be able to use the application.
- Locate the existing Path environment variable in the list of variables for either the personal or system environment variables and click Edit. If there is no existing Path environment variable, click New instead. You see a dialog box similar to the one shown here.
- When adding a new variable, type Path in the Variable Name field.
- Add the path you want to use in the Variable Value field. Click OK three times to close all the dialog boxes.
Set PATH and other environment variables in Windows 10
In older windows systems you had to navigate to Advanced System Settings in Control Panel to view, edit or add environmental variables.
- Windows XP — Right-click My Computer, and then click Properties → Advanced → Environment variables → Choose New, Edit or Delete.
- Windows 7 — Click on Start → Computer → Properties → Advanced System Settings → Environment variables → Choose New, Edit or Delete.
In Windows 8 and 10, you can navigate to Advanced System Settings in a similar way.
- Windows 8 — Right click on bottom left corner to get Power User Task Menu → Select System → Advanced System Settings → Environment variables → Choose New, Edit or Delete.
- Windows 10 — Right click on Start Menu to get Power User Task Menu → Select System → Advanced System Settings → Environment variables → Choose New, Edit or Delete.
However, in Windows 10 you can directly get to the Environment Variables window using Search the web and Windows box next to the Start menu. Type environment variables in Windows Search box which gives you two options in search results:
- Edit the system environment variables
- Edit environment variables for your account.
Choose either option and you can add, edit or delete environment variables like PATH.
Set environment variables from command prompt
You can set environment variables from Windows Command Prompt using the set or setx command. The set command only sets the environment variable for the current session. The setx command sets it permanently, but not for the current session. If you want to set it for current as well as future sessions, use both setx and set.
For example, you can set the PATH environment variable permanently (current and future sessions) as below:
To view the current path, run:
- By default setx sets the variable in the local environment (Under HKEY_Current_User Registry key). If you want to set the system variable (Under HKEY_LOCAL_MACHINE registry key), use the flag /m. Start the command prompt as administrator on Windows 10, right click on Start menu and select Command Prompt(Admin).
- The maximum value allowed for a enviroment variable is 1024 characters. So if your variable is long and you try to append to it with setx, you may get a truncated result.
Set environment variable by Registry edit
If your PATH variable is too long, then the best method would be to edit the registry.
For user environment variables, change the key HKEY_CURRENT_USER\Environment . For System Environment variables change
Add, Edit or Delete the environment variable you want to change, then reboot to activate the changes.