Меню Рубрики

Add linux path variable

Переменная 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 и как добавлять к её значению новые пути поиска исполняемых и связанных с ними файлов. Как видите, всё делается достаточно просто. Таким образом вы можете добавить столько папок для поиска и хранения исполняемых файлов, сколько вам требуется.

Источник

Adding a Path to the Linux PATH Variable

Last modified: May 8, 2020

1. Overview

In this quick tutorial, we’ll focus on how to add a path to the Unix PATH variable.

2. PATH Variable

The PATH variable is an environment variable that contains an ordered list of paths that Unix will search for executables when running a command. Using these paths means that we do not have to specify an absolute path when running a command.

For example, if we want to print Hello, world!, the command echo can be used rather than /bin/echo so long as /bin is in PATH:

Unix traverses the colon-separated paths in order until finding an executable. Thus, Unix uses the first path if two paths contain the desired executable.

We can print the current value of the PATH variable by echoing the PATH environment variable:

We should see a list of colon-separated paths (exact paths may differ):

3. Adding a New Path

We add a new path to the PATH variable using the export command.

To prepend a new path, such as /some/new/path, we reassign the PATH variable with our new path at the beginning of the existing PATH variable (represented by $PATH):

To append a new path, we reassign PATH with our new path at the end:

4. Persisting Changes

When we use the export command and open a new shell, the added path is lost.

4.1. Locally

To persist our changes for the current user, we add our export command to the end of

/.profile file doesn’t exist, we should create it using the touch command:

Then we can add our export command to

Additionally, we need to open a new shell or source our

/.profile file to reflect the change. We’d either execute:

or we could use the source command if we are using Bash:

We could also append our export command to

/.bash_profile if we are using Bash, but our changes will be not be reflected in other shells, such as Z shell (zsh). We shouldn’t add our export command to

/.bashrc because only interactive Bash shells read this configuration file. If we open a non-interactive shell or a shell other than Bash, our PATH change will not be reflected.

4.2. Globally

We can add a new path for all users on a Unix system by creating a file ending in .sh in /etc/profile.d/ and adding our export command to this file.

For example, we can create a new script file, /etc/profile.d/example.sh, and add the following line to append /some/new/path to the global PATH:

All of the scripts in /etc/profile.d/ will be executed when a new shell initializes. Therefore, we need to open a new shell for our global changes to take effect.

We can also add our new path directly to the existing PATH in the /etc/environment file:

The /etc/environment file is not a script file—it only contains simple variable assignments—and is less flexible than a script. Because of this, making PATH changes in /etc/environment is discouraged. We recommend adding a new script to /etc/profile.d instead.

5. Conclusion

In this tutorial, we saw how Unix uses the PATH variable to find executables when running a command.

We can prepend or append to PATH, but we must persist these changes in

Источник

How to permanently set $PATH on Linux/Unix? [closed]

Want to improve this question? Update the question so it’s on-topic for Stack Overflow.

I’m trying to add a directory to my path so it will always be in my Linux path. I’ve tried:

This works, however each time I exit the terminal and start a new terminal instance, this path is lost, and I need to run the export command again.

How can I do it so this will be set permanently?

24 Answers 24

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 and export or set commands.

System wide

  1. /etc/environment List of unique assignments, allows references. Perfect for adding system-wide directories like /usr/local/something/bin to PATH variable or defining JAVA_HOME . Used by PAM and SystemD.
  2. /etc/environment.d/*.conf List of unique assignments, allows references. Perfect for adding system-wide directories like /usr/local/something/bin to PATH variable or defining JAVA_HOME . The configuration can be split into multiple files, usually one per each tool (Java, Go, NodeJS). Used by SystemD that by design do not pass those values to user login shells.
  3. /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.
  4. /etc/profile and /etc/profile.d/* Shell script. This is a good choice for shell-only systems. Those files are read only by shells in login mode.
  5. /etc/ . rc . Shell script. This is a poor choice because it is single shell specific. Used in non-login mode.

User session

/.pam_environment . List of unique assignments, no references allowed. 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 variables including HOME or PATH so it has limited use. Used by PAM.

/.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.

/. _login Shell script. It will be visible only for programs started from terminal or terminal emulator. It is a good choice for shell-only systems. Used by shells in login mode.

/. rc . Shell script. This is a poor choice because it is single shell specific. Used by shells in non-login mode.

Notes

Gnome on Wayland starts user login shell to get the environment. It effectively uses login shell configurations

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

  • Bluetooth адаптер для mac os
  • Bluetooth explorer mac os
  • Blackmagic disk speed test mac os
  • Blackberry link для mac os
  • Blackberry desktop software for mac os