Переменная path linux debian

Как и куда правильно прописать PATH?

На Debian необходимо прописать переменную PATH, но что-то не один из известных мне способов не помогает.

Куда прописать PATH, чтобы не делать это при каждой сессии?!

/.cshrc на FreeBSD. В Debian, скорее всего, похожий механизм.

только у автора вопроса не csh. Но вы довольно близко угадали.

В Debian есть .bashrc, как я понял это аналог, но я хз как правильно это сделать

Не за что, неосилятор.

Та я много чего перепробовал — ничего не помогло. Так я еще не пробовал.

имелось ввиду, удлинить PATH, записав это в

/.profile. Есть и ещё возможные места, но эти популярны в случае, если надо задать PATH или иную переменную для текущего пользователя. Вообще-то, между ними есть некоторая разница. Здесь

это краткая замена для имени домашней папки текущего пользователя, но можно её записывать и в явном виде.

В /etc/environment можно

Я прописывал в /etc/environment, но наверное не правильно, ибо не помогло. Прописал в .bashrc — помогло

Источник

Переменная 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 и вручную дописать туда нужное значение:

Можно поступить и иначе. Содержимое файла .bashrc выполняется при каждом запуске оболочки Bash. Если добавить в конец файла команду export, то для каждой загружаемой оболочки будет автоматически выполняться добавление имени требуемой папки в переменную PATH, но только для текущего пользователя:

Источник

  • ru
  • EnvironmentVariables

Общая информация

Переменные окружения (среды́) это переменные (хранящие значение типа Строка) которые оказывают влияние на работу множества утилит, функций, приложений. Переменные используются для адаптации поведения каждого приложения к конкретному Окружению в котором оно исполняется. Например, вы можете задать пути к файлам, языковые параметры, и т.д. Перечень переменных к которым обращается приложение вы можете посмотреть в его инструкции.

Читайте также:  Как восстановить стертые файлы windows

Тем не менее существует несколько стандартных для Linux переменных окружения:

  • PATH = Список директорий (разделенных двоеточиями) в которых следует искать исполняемые файлы соответствующие командам.
  • HOME = Домашняя директория текущего пользователя.
  • LOGNAME = Имя текущего пользователя.
  • SHELL = Командный интерпретатор по-умолчанию для текущего пользователя.
  • EDITOR = Текстовый редактор по-умолчанию для текущего пользователя.
  • MAIL = Путь к каталогу, в котором должны храниться файлы входящей электронной почты текущего пользователя

Вы можете посмотреть переменные вашего текущего Окружения если откроете терминал и выполните команду ‘env’. To see your currently defined variables, open up your terminal and type the env command.

Переменные объявляются с помощью пары имя-значение: NAME=any string as value Variables are defined with name-value pairs: NAME=any string as value. Имя переменной обычно состоит из заглавных букв. The variable name is usually in capital letters. Всё что следует после «знака равно (=)» и до символа переноса строки воспринимается как значение переменной. Anything that follows the equal-sign is considered the variable’s value until the terminating line feed character. Переменные можно определить «на лету» (в любое время) выполнив в терминале нужную команду. Variables can be defined ad hoc in a terminal by writing the appropriate command. Для Интерпретатора Bash эта команда будет выглядеть следующим образом: export MYVAL=»Hello world». In Bash this would be export MYVAL=»Hello world». В этом случае переменная будет «жить»пока «жива» терминальная сессия. In this case the variable stays defined until the end of the terminal session.

Если вы хотите дополнить значение переменной вместо того чтобы полностью перезаписать его, то включите имя переменной в новое определение. If you want to append something to a variable, instead of overwriting the previous value, include the variable name into the new definition. Например для Bash: export PATH=$PATH:

/bin (E.g. in Bash: export PATH=$PATH:

/bin.)— Этот пример показывает как добавить путь к папке bin расположенной в домашней директории пользователя в переменную Окружения PATH This example shows how to append the bin directory in the user’s home directory onto the PATH environment variable.

Существует возможность обеспечить автоматическое определение переменных — достаточно прописать соответствующие строки в конфигурационных файлах которые считываются в процесс запуска системы или авторизации пользователя. In most cases it is most convenient to store these variables in a configuration file that is read during system boot and user login so that they are available automatically. К сожалению, это не так просто как кажется. Unfortunately this not always as easy as it sounds. Почему? Why? По нескольким причинам: For a couple of reasons:

Переменные окружения являются наследуемыми; т.е. программа-родитель задает окружение для дочернего процесса. Environment variables are inherited; i.e., the parent program sets the environment for the child process. Вам необходимо корректировать настройки родительской программы для того, чтобы они были унаследованы дочерними процессами. You need to configure the parent’s settings so that it passes it on for all its children.

Скорее всего этими родительскими процессами окажутся какая-нибудь командная оболочка и какой-нибудь оконный менеджер, и каждый из эти процессов будет брать свои настройки из собственного конфигурационного файла (dot file) в процессе запуска. Various shells and window managers are the parent programs we are looking for but each of them reads a different configuration file (dot file) when it starts.

Зная это мы приходим к пониманию, что нам необходимо отслеживать порядок запуска обоих системных процессов и изучить конфигурационные файлы которые они считывают. So, with this knowledge we understand that we need to consider both the starting order of system processes and the configuration files they read when they are started. См. страницу посвещенную конфигурационным файлам (DotFiles) или читайте дальше See the DotFiles page, or read on .

Поехали! Lets get to it! Есть два пути взаимодействия с Линукс: текстовая консоль или графический интерфейс There are two ways you can run your Linux box: from text console or graphical user interface .

Использование текстовой консоли

После авторизации в текстовой консоли мы оказываемся в пользовательской командной оболочке. Text console logins end up with a login shell. Variables are acquired in stages, by multiple processes in sequence. Каждый процесс добавляет ещё больше переменных. Each process adds some more variables .

Читайте также:  Даты выхода всех версий windows

При включении системы запускается процесс init — он является родитеским для всех других процессов. At the end of boot the mother of all processes init is started. Окружение процесса init включает переменную PATH, эта переменная определена в исходных кодах процесса и не может быть изменена во время исполнения. init‘s environment, including PATH, is defined in its source code and cannot be changed at run time .

init запускает загрузочные скрипты из /lib/systemd/system (система инициализации systemd) или /etc/rc?.d в соответствии с порядком описанном в /etc/inittab (система инициализации sysvinit) init runs the start-up scripts from /lib/systemd/system (under systemd) or /etc/rc?.d based on the run level set in /etc/inittab (under sysvinit). Каждая служба или скрипт определяет в своём окружении собственные переменные. Each service or script defines its own required environment variables.

General

Environment variables are named strings available to all applications. Variables are used to adapt each application’s behavior to the environment it is running in. You might define paths for files, language options, and so on. You can see each application’s manual to see what variables are used by that application.

That said, there are several standard variables in Linux environments:

  • PATH = Colon separated list of directories to search for commands.
  • HOME = Current user’s home directory.
  • LOGNAME = Current user’s name.
  • SHELL = The user’s preferred shell.
  • EDITOR = The user’s preferred text editor.
  • MAIL = The user’s electronic mail inbox location.

To see your currently defined variables, open up your terminal and type the env command.

Variables are defined with name-value pairs: NAME=any string as value. The variable name is usually in capital letters. Anything that follows the equal-sign is considered the variable’s value until the terminating line feed character. Variables can be defined ad hoc in a terminal by writing the appropriate command. In Bash this would be export MYVAL=»Hello world». In this case the variable stays defined until the end of the terminal session.

If you want to append something to a variable, instead of overwriting the previous value, include the variable name into the new definition. E.g. in Bash: export PATH=$PATH:

/bin. This example shows how to append the bin directory in the user’s home directory onto the PATH environment variable.

In most cases it is most convenient to store these variables in a configuration file that is read during system boot and user login so that they are available automatically. Unfortunately this not always as easy as it sounds. Why? For a couple of reasons:

  1. Environment variables are inherited; i.e., the parent program sets the environment for the child process. You need to configure the parent’s settings so that it passes it on for all its children.
  2. Various shells and window managers are the parent programs we are looking for but each of them reads a different configuration file (dot file) when it starts.

So, with this knowledge we understand that we need to consider both the starting order of system processes and the configuration files they read when they are started. See the DotFiles page, or read on .

Lets get to it! There are two ways you can run your Linux box: from text console or graphical user interface.

Using text console

Text console logins end up with a login shell. Variables are acquired in stages, by multiple processes in sequence. Each process adds some more variables.

At the end of boot the mother of all processes init is started. init‘s environment, including PATH, is defined in its source code and cannot be changed at run time.

init runs the start-up scripts from /lib/systemd/system (under systemd) or /etc/rc?.d based on the run level set in /etc/inittab (under sysvinit). Each service or script defines its own required environment variables.

At the end of booting, init runs a getty process on one or more virtual consoles. getty waits for the user to type their name, after which it sets the TERM variable and executes login to prompt for a password.

Читайте также:  Linux samba как расшарить

login checks /etc/passwd and /etc/shadow for the user’s account details. If the password is acceptable, login sets HOME, SHELL, PATH, LOGNAME and MAIL based on the contents of /etc/passwd, checks PAM, and finally runs the user’s login shell.

PAM may instruct login to read the variables in /etc/environment also. This is the default.

The login shell starts and reads its shell-specific configuration files.

    bash first reads /etc/profile to get values that are defined for all users. After reading that file, it looks for

    /.profile, in that order, and reads and executes commands from the first of these files that exists and is readable. See DotFiles for full details.

  1. (please fill in other shells as well)

Now the environment variables are ready to be used by the applications you start from the terminal.

Using graphical display manager

The login process is quite different under a DisplayManager.

At the end of booting, the mother of all processes — init — is started.

init runs services as described above. One of these services will be your display manager.

When the user successfully logs in, the display manager checks PAM, and then starts an Xsession.

PAM may instruct the DM to read the variables from /etc/environment.

The Xsession reads

/.xsessionrc and possibly other files depending on the session type.

Graphical logins do not read a shell’s startup files ( /etc/profile and

/.profile and so on) by default, but you as a user may choose to create a

/.xsessionrc file which does this.

Quick guide

For the hasty who just need to get the system running, here is what you can do:

Put all global environment variables, i.e. ones affecting all users, into /etc/environment

Remember, this file is read by PAM, not by a shell. You cannot use shell expansions here. E.g. MAIL=$HOME/Maildir/ will not work!

There is no shell-agnostic and login-independent solution to the problem of how to configure the environment for all users, beyond the trivial cases that PAM can handle.

Put all your transient shell settings (aliases, functions, shell options) in

Put all your environment variables in

Create or edit file

/.bash_profile and include commands:

Create or edit file

/.xsessionrc and include the same commands as above.

This is a quicky and dirty approach! Not for the pedantic user.

Notes and exceptions

startx from terminal

If you start X Window (the GUI) from a text console, your environment variables are already defined by your login shell, as explained above. However, the window manager may read the same files again (see below). This is usually not a problem, but you may get unexpected results, such as PATH having all entries listed twice.

Shell cascading

If you start another shell within the login shell (yes it is possible), the second one is a non-login shell. It will not read named start-up files but searches non-login start-up script from user’s home directory instead. With Bash it is called

/.bashrc. To avoid specifying same values in two places usually the login-shell start-up script

/.bash_profile includes the

/.bashrc at the end of its execution. To implement include following into your

Terminal windows in X

If you start terminal / console window in graphical desktop environment it will be non-login terminal and it will read only the user’s non-login start-up script. For Bash this is

Using su

The su command is used to become another user during a login session. It is commonly used to get root permissions temporarily from normal session. In Stretch and earlier releases, the su command resets your PATH environment value to one defined in /etc/login.defs by ENV_PATH and ENV_SUPATH variables. In Buster, su does not change your PATH variable.

Please note that using Gnome helper gksu from Gnome panel by default uses su internally (i.e. you may «lose» your PATH if you do not configure it in login.defs in stretch).

Does this mean gksu simply fails outright in buster due to the missing /sbin et al. in PATH?

Источник

Оцените статью