Переменная PATH в Linux
Когда вы запускаете программу из терминала или скрипта, то обычно пишете только имя файла программы. Однако, ОС Linux спроектирована так, что исполняемые и связанные с ними файлы программ распределяются по различным специализированным каталогам. Например, библиотеки устанавливаются в /lib или /usr/lib, конфигурационные файлы в /etc, а исполняемые файлы в /sbin/, /usr/bin или /bin.
Таких местоположений несколько. Откуда операционная система знает где искать требуемую программу или её компонент? Всё просто — для этого используется переменная PATH. Эта переменная позволяет существенно сократить длину набираемых команд в терминале или в скрипте, освобождая от необходимости каждый раз указывать полные пути к требуемым файлам. В этой статье мы разберёмся зачем нужна переменная PATH Linux, а также как добавить к её значению имена своих пользовательских каталогов.
Переменная PATH в Linux
Для того, чтобы посмотреть содержимое переменной PATH в Linux, выполните в терминале команду:
На экране появится перечень папок, разделённых двоеточием. Алгоритм поиска пути к требуемой программе при её запуске довольно прост. Сначала ОС ищет исполняемый файл с заданным именем в текущей папке. Если находит, запускает на выполнение, если нет, проверяет каталоги, перечисленные в переменной PATH, в установленном там порядке. Таким образом, добавив свои папки к содержимому этой переменной, вы добавляете новые места размещения исполняемых и связанных с ними файлов.
Для того, чтобы добавить новый путь к переменной PATH, можно воспользоваться командой export. Например, давайте добавим к значению переменной PATH папку/opt/local/bin. Для того, чтобы не перезаписать имеющееся значение переменной PATH новым, нужно именно добавить (дописать) это новое значение к уже имеющемуся, не забыв о разделителе-двоеточии:
Теперь мы можем убедиться, что в переменной PATH содержится также и имя этой, добавленной нами, папки:
Вы уже знаете как в Linux добавить имя требуемой папки в переменную PATH, но есть одна проблема — после перезагрузки компьютера или открытия нового сеанса терминала все изменения пропадут, ваша переменная PATH будет иметь то же значение, что и раньше. Для того, чтобы этого не произошло, нужно закрепить новое текущее значение переменной PATH в конфигурационном системном файле.
В ОС Ubuntu значение переменной PATH содержится в файле /etc/environment, в некоторых других дистрибутивах её также можно найти и в файле /etc/profile. Вы можете открыть файл /etc/environment и вручную дописать туда нужное значение:
sudo vi /etc/environment
Можно поступить и иначе. Содержимое файла .bashrc выполняется при каждом запуске оболочки Bash. Если добавить в конец файла команду export, то для каждой загружаемой оболочки будет автоматически выполняться добавление имени требуемой папки в переменную PATH, но только для текущего пользователя:
Выводы
В этой статье мы рассмотрели вопрос о том, зачем нужна переменная окружения PATH в Linux и как добавлять к её значению новые пути поиска исполняемых и связанных с ними файлов. Как видите, всё делается достаточно просто. Таким образом вы можете добавить столько папок для поиска и хранения исполняемых файлов, сколько вам требуется.
Источник
Where is PATH variable set in Ubuntu? [duplicate]
This is a very interesting question that I stumbled upon when I was creating a command-line application tool for Linux. Unfortunately, the answer on SO is so hidden among the myriad answers to other questions that I decided to ask another question on SO for those who want to modify PATH programmatically.
2 Answers 2
Grzegorz Żur’s answer to another question captures it brilliantly. Unfortunately it was hidden away among many other answers.
There are multiple ways to do it. The actual solution depends on the purpose.
The variable values are usually stored in either a list of assignments or a shell script that is run at the start of the system or user session. In case of the shell script you must use a specific shell syntax.
System wide
- /etc/environment List of unique assignments. Perfect for adding system-wide directories like /usr/local/something/bin to PATH variable or defining JAVA_HOME .
- /etc/xprofile Shell script executed while starting X Window System session. This is run for every user that logs into X Window System. It is a good choice for PATH entries that are valid for every user like /usr/local/something/bin . The file is included by other script so use POSIX shell syntax not the syntax of your user shell.
- /etc/profile and /etc/profile.d/* Shell script. This is a good choice for shell-only systems. Those files are read only by shells.
- /etc/ . rc . Shell script. This is a poor choice because it is single shell specific.
Also, /etc/environment is not a script file, but rather consists of assignment expressions, one per line. Since this file stores the system-wide locale and path settings, it is most oft quoted choice. Using /etc/profile is not preferred. It exists only to point to /etc/bash.bashrc and to collect entries from /etc/profile.d
User session
/.pam_environment . List of unique assignments. Loaded by PAM at the start of every user session irrelevant if it is an X Window System session or shell. You cannot reference other variable including HOME or PATH so it has limited use.
/.xprofile Shell script. This is executed when the user logs into X Window System system. The variables defined here are visible to every X application. Perfect choice for extending PATH with values such as
/go/bin or defining user specific GOPATH or NPM_HOME . The file is included by other script so use POSIX shell syntax not the syntax of your user shell. Your graphical text editor or IDE started by shortcut will see those values.
/.profile Shell script. It will be visible only for programs started from terminal or terminal emulator. It is a good choice for shell-only systems.
/. rc . Shell script. This is a poor choice because it is single shell specific.
Источник
Как изменить переменную Path в Linux
wikiHow работает по принципу вики, а это значит, что многие наши статьи написаны несколькими авторами. При создании этой статьи над ее редактированием и улучшением работали авторы-волонтеры.
Количество просмотров этой статьи: 42 610.
Операционные системы обычно используют переменные окружения для определения глобальных настроек или для контроля работы программ. Переменная Path является одной из переменных окружения и постоянно используется без вашего ведома. Переменная хранит список каталогов, в которых расположены исполняемые файлы.
$ echo $PATH/home/uzair/bin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/games
$ echo $PATH/home/uzair/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
Источник
How can I edit the $PATH on linux?
I am using ubuntu 9.04 I need to add some folder to my $PATH. I know how to read the path:
I want to be able to edit it and add 2 other paths.
8 Answers 8
To permanently store your path, you have a few options.
I suggest you read the Ubuntu community wiki on Environment Variables but the short answer is the best place is
/.profile for your per-user PATH setting or /etc/profile for global settings.
Do something like export PATH=$PATH:/your/new/path/here
You can also put this in the global environment:
Append to the entries already in your path
Reload the environment
It has already been answered on how to do that, but I’d like to give you a little tip. Here is whatI do:
I have a directory called .bash.d in my $HOME and within that I keep a set of shell scripts that do stuff to my environment (for instance setup maven correctly, modify the path, set my prompt etc.). I keep this under version control by using git, which makes it easy to go back to a working version of your env, if you screw something up badly. To get all the modifications, I simply source all files in that dir at the end of my .bashrc like this:
This gives you a very flexible environment that you can easily modify and restore + you are able to export it to other machines just by using git.
Источник
How to add a directory to the PATH?
How do I add a directory to the $PATH in Ubuntu and make the changes permanent?
17 Answers 17
Using
/.profile to set $PATH
A path set in .bash_profile will only be set in a bash login shell ( bash -l ). If you put your path in .profile it will be available to your complete desktop session. That means even metacity will use it.
Btw, you can check the PATH variable of a process by looking at its environment in /proc/[pid]/environ (replace [pid] with the number from ps axf ). E.g. use grep -z «^PATH» /proc/[pid]/environ
bash as a login shell doesn’t parse .profile if either .bash_profile or .bash_login exists. From man bash :
/.profile, in that order, and reads and executes commands from the first one that exists and is readable.
See the answers below for information about .pam_environment , or .bashrc for interactive non-login shells, or set the value globally for all users by putting a script into /etc/profile.d/ or use /etc/X11/Xsession.d/ to affect the display managers session.
Edit .bashrc in your home directory and add the following line:
You will need to source your .bashrc or logout/login (or restart the terminal) for the changes to take effect. To source your .bashrc , simply type
The recommended place to define permanent, system-wide environment variables applying to all users is in:
(which is where the default PATH is defined)
This will work in desktop or console, gnome-terminal or TTY, rain or shine 😉
To edit, open the terminal and type:
(or open the file using sudo in your favorite text editor)
To make it work without rebooting, run . /etc/environment or source /etc/environment . Since this file is just a simple script it will run and assign the new path to the PATH environment variable. To check run env and see the PATH value in the listing.
I think the canonical way in Ubuntu is:
create a new file under /etc/profile.d/
and give it execute permission
For complete newbies (like I am) who are more comfortable with GUI:
- Open your $HOME folder.
- Go to View → Show Hidden Files or press Ctrl + H .
- Right click on .profile and click on Open With Text Editor.
- Scroll to the bottom and add PATH=»$PATH:/my/path/foo» .
- Save.
- Log out and log back in to apply changes (let Ubuntu actually load .profile ).
For persistent environment variables available to particular users only. I highly recommend Ubuntu official documentation.
Referring to documentation above, I have setup my Android SDK path-tools by:
/.pam_environment file in home directory.
the content of which is PATH DEFAULT=$
/android-sdk-linux/tools .
Put that line in your
It gets sourced whenever you open a terminal
EDIT: Based on the comments below, for a more general setting that will apply to all shells (including when you hit Alt — F2 in Unity), add the line to your
/.profile file. Probably shouldn’t do both however, as the path will be added twice to your PATH environment if you open a terminal.
/.bashrc , it’ll only be available in the terminals you open. E.g. if you hit Alt+F2 and try to run a command from that dir, it won’t find it. If you set it in
/.pam_environment , the gnome session (or whichever DE you use) will inherit it. Appending PATH in
/.bashrc also has the drawback that if you open/exec bash interactively from another interactive bash shell, it’ll be appended multiple times.
/.profile is correct for personal paths, though; that’s where Ubuntu adds the
/bin directory. And I confess that I exaggerated a slight bit on the number of ways — just a little.
/.profile in this case too.
To set it system wide, append the line export PATH=/path/you’re/adding:$PATH to the end of /etc/profile .
To add the directory for only the logged-in user, append the same line to
Adding it to .bashrc will work but I think the more traditional way of setting up your path variables is in .bash_profile by adding the following lines.
According to this thread it appears as though Ubuntu’s behavior is slightly different than RedHat and clones.
In terminal, cd to the_directory_you_want_to_add_in_the_path
This wasn’t my idea. I found this way to export path at this blog here.
The recommended way to edit your PATH is from /etc/environment file
Example output of /etc/environment :
For example, to add the new path of /home/username/mydir
Then, reboot your PC.
System-wide environment variables
A suitable file for environment variable settings that affect the system as a whole (rather than just a particular user) is /etc/environment. An alternative is to create a file for the purpose in the /etc/profile.d directory.
/etc/environment
This file is specifically meant for system-wide environment variable settings. It is not a script file, but rather consists of assignment expressions, one per line.
Note: Variable expansion does not work in /etc/environment.
More info can be found here: EnvironmentVariables
Источник