Linux add path to executable

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

Источник

How do I add an executable to my search path?

For reference, I know very little about Linux, and am using it to run a program written by someone else. The instructions say Add the executable ‘ttt’ to the search path. In most installations this can be accomplished by linking the file to the ‘bin’ subdirectory at user home.

How do I go about doing this?

This executable is currently in a subfolder in the host area, as it’s running on a dual-boot computer I cannot change the fact that it is a dual boot, as it is a work computer.

1 Answer 1

To make this work for the command line (terminal):

I would suggest that you do the following steps in the terminal:

Create a folder called bin in your home directory.

/bin to your PATH for all sessions of Bash (the default shell used inside of the terminal).

Читайте также:  Почему при синхронизации времени windows

Add either the executable files themselves OR symlinks to the executable into

Restart your terminal session by closing out the terminal and reopening it, or run source

/.bashrc to reload the configuration for your session

That should allow your terminal to read the PATH variable for terminal sessions.

I do not know how to add it to the GUI, though, as I’m not certain of how the GUI manages the PATH variable(s), but it might be necessary to modify the path with other methods should this method here not work with the GUI.

Источник

How to correctly add a path to PATH?

I’m wondering where a new path has to be added to the PATH environment variable. I know this can be accomplished by editing .bashrc (for example), but it’s not clear how to do this.

12 Answers 12

The simple stuff

depending on whether you want to add

/opt/bin at the end (to be searched after all other directories, in case there is a program by the same name in multiple directories) or at the beginning (to be searched before all other directories).

You can add multiple entries at the same time. PATH=$PATH:

/opt/node/bin or variations on the ordering work just fine. Don’t put export at the beginning of the line as it has additional complications (see below under “Notes on shells other than bash”).

If your PATH gets built by many different components, you might end up with duplicate entries. See How to add home directory path to be discovered by Unix which command? and Remove duplicate $PATH entries with awk command to avoid adding duplicates or remove them.

Some distributions automatically put

/bin in your PATH if it exists, by the way.

Where to put it

Put the line to modify PATH in

/.bash_profile if that’s what you have.

/.bash_rc is not read by any program, and

/.bashrc is the configuration file of interactive instances of bash. You should not define environment variables in

/.bashrc . The right place to define environment variables such as PATH is

/.bash_profile if you don’t care about shells other than bash). See What’s the difference between them and which one should I use?

Don’t put it in /etc/environment or

/.pam_environment : these are not shell files, you can’t use substitutions like $PATH in there. In these files, you can only override a variable, not add to it.

Potential complications in some system scripts

You don’t need export if the variable is already in the environment: any change of the value of the variable is reflected in the environment.¹ PATH is pretty much always in the environment; all unix systems set it very early on (usually in the very first process, in fact).

At login time, you can rely on PATH being already in the environment, and already containing some system directories. If you’re writing a script that may be executed early while setting up some kind of virtual environment, you may need to ensure that PATH is non-empty and exported: if PATH is still unset, then something like PATH=$PATH:/some/directory would set PATH to :/some/directory , and the empty component at the beginning means the current directory (like .:/some/directory ).

Notes on shells other than bash

In bash, ksh and zsh, export is special syntax, and both PATH=

/opt/bin:$PATH and export PATH=

/opt/bin:$PATH do the right thing even. In other Bourne/POSIX-style shells such as dash (which is /bin/sh on many systems), export is parsed as an ordinary command, which implies two differences:

is only parsed at the beginning of a word, except in assignments (see How to add home directory path to be discovered by Unix which command? for details);

  • $PATH outside double quotes breaks if PATH contains whitespace or \[*? .
  • So in shells like dash, export PATH=

    /opt/bin:$PATH sets PATH to the literal string

    /opt/bin/: followed by the value of PATH up to the first space. PATH=

    /opt/bin:$PATH (a bare assignment) doesn’t require quotes and does the right thing. If you want to use export in a portable script, you need to write export PATH=»$HOME/opt/bin:$PATH» , or PATH=

    Читайте также:  Windows 10 pro x64 оригинальный образ 2019

    /opt/bin:$PATH; export PATH (or PATH=$HOME/opt/bin:$PATH; export PATH for portability to even the Bourne shell that didn’t accept export var=value and didn’t do tilde expansion).

    ¹ This wasn’t true in Bourne shells (as in the actual Bourne shell, not modern POSIX-style shells), but you’re highly unlikely to encounter such old shells these days.

    /.bashrc«, but unfortunately 100% of the programs that I have installed on my system that modify the path (FZF and Rust’s Cargo) modify the path in .bashrc . I assume because FZF is written in Rust too it’s following the pattern of Rust.

    Either way works, but they don’t do the same thing: the elements of PATH are checked left to right. In your first example, executables in

    /opt/bin will have precedence over those installed, for example, in /usr/bin , which may or may not be what you want.

    In particular, from a safety point of view, it is dangerous to add paths to the front, because if someone can gain write access to your

    /opt/bin , they can put, for example, a different ls in there, which you’d then probably use instead of /bin/ls without noticing. Now imagine the same for ssh or your browser or choice. (The same goes triply for putting . in your path.)

    The bullet-proof way of Appending/Prepending

    Try not using

    Why? There are a lot of considerations involved in the choice of appending versus prepending. Many of them are covered in other answers, so I will not repeat them here.

    An important point is that, even if system scripts do not use this (I wonder why) *1 , the bullet-proof way to add a path (e.g.,

    /opt/bin ) to the PATH environment variable is

    for appending (instead of PATH=»$PATH:

    for prepending (instead of PATH=»

    This avoids the spurious leading/trailing colon when $PATH is initially empty, which can have undesired side effects and can become a nightmare, elusive to find (this answer briefly deals with the case the awk -way).

    If parameter is null or unset, nothing is substituted, otherwise the expansion of word is substituted.

    1. nothing, if PATH is null or unset,
    2. $: , if PATH is set.

    Note: This is for bash.

    *1 I have just found that scripts like `devtoolset-6/enable` actually use this,

    I’m confused by question 2 (since removed from the question since it was due to an unrelated issue):

    What’s a workable way to append more paths on different lines? Initially I thought this could do the trick:

    but it doesn’t because the second assignment doesn’t only append

    /opt/node/bin , but also the whole PATH previously assigned.

    This is a possible workaround:

    but for readability I’d prefer to have one assignment for one path.

    that’s all that will be in your PATH. PATH is just an environment variable, and if you want to add to the PATH, you have to rebuild the variable with exactly the contents you want. That is, what you give as an example to question 2 is exactly what you want to do, unless I’m totally missing the point of the question.

    I use both forms in my code. I have a generic profile that I install on every machine I work on that looks like this, to accommodate for potentially-missing directories:

    Linux determines the executable search path with the $PATH environment variable. To add directory /data/myscripts to the beginning of the $PATH environment variable, use the following:

    To add that directory to the end of the path, use the following command:

    But the preceding are not sufficient because when you set an environment variable inside a script, that change is effective only within the script. There are only two ways around this limitation:

    • If within the script, you export the environment variable it is effective within any programs called by the script. Note that it is not effective within the program that called the script.
    • If the program that calls the script does so by inclusion instead of calling, any environment changes in the script are effective within the calling program. Such inclusion can be done with the dot command or the source command.

    Inclusion basically incorporates the «called» script in the «calling» script. It’s like a #include in C. So it’s effective inside the «calling» script or program. But of course, it’s not effective in any programs or scripts called by the calling program. To make it effective all the way down the call chain, you must follow the setting of the environment variable with an export command.

    As an example, the bash shell program incorporates the contents of file .bash_profile by inclusion. Place the following 2 lines in .bash_profile:

    effectively puts those 2 lines of code in the bash program. So within bash, the $PATH variable includes $HOME/myscript.sh , and because of the export statement, any programs called by bash have the altered $PATH variable. And because any programs you run from a bash prompt are called by bash, the new path is in force for anything you run from the bash prompt.

    The bottom line is that to add a new directory to the path, you must append or prepend the directory to the $PATH environment variable within a script included in the shell, and you must export the $PATH environment variable.

    Источник

    Как добавить каталог в PATH в Linux

    Когда вы вводите команду в командной строке, вы в основном говорите оболочке запустить исполняемый файл с заданным именем. В Linux эти исполняемые программы, такие как ls , find , file и другие, обычно find в нескольких разных каталогах вашей системы. Любой файл с исполняемыми разрешениями, хранящийся в этих каталогах, может быть запущен из любого места. Наиболее распространенные каталоги, содержащие исполняемые программы, — это /bin , /sbin , /usr/sbin , /usr/local/bin и /usr/local/sbin .

    Но как оболочка узнает, в каких каталогах искать исполняемые программы? Оболочка выполняет поиск по всей файловой системе?

    Ответ прост. Когда вы вводите команду, оболочка просматривает все каталоги, указанные в $PATH пользователя, в поисках исполняемого файла с таким именем.

    В этой статье показано, как добавить каталоги в $PATH в системах Linux.

    Что такое $PATH в Linux

    Переменная среды $PATH представляет собой список каталогов, разделенных двоеточиями, который сообщает оболочке, в каких каталогах следует искать исполняемые файлы.

    Чтобы проверить, какие каталоги находятся в вашем $PATH , вы можете использовать команду printenv или echo :

    Результат будет выглядеть примерно так:

    Если у вас есть два исполняемых файла с одинаковым именем, расположенных в двух разных каталогах, оболочка запустит файл, который находится в каталоге, который идет первым в $PATH .

    Добавление каталога в ваш $PATH

    Бывают ситуации, когда вы можете захотеть добавить другие каталоги в $PATH . Например, некоторые программы могут быть установлены в разных местах или вы можете захотеть иметь специальный каталог для ваших личных сценариев, но иметь возможность запускать их, не указывая абсолютный путь к исполняемым файлам. Для этого вам просто нужно добавить каталог в ваш $PATH .

    Допустим, у вас есть каталог bin расположенный в вашем домашнем каталоге, в котором вы храните сценарии оболочки. Чтобы добавить каталог в ваш $PATH введите:

    Команда export экспортирует измененную переменную в среду дочернего процесса оболочки.

    Теперь вы можете запускать свои сценарии, вводя имя исполняемого сценария без необходимости указывать полный путь к файлу.

    Однако это изменение носит временный характер и действует только в текущем сеансе оболочки.

    Чтобы сделать изменение постоянным, вам необходимо определить $PATH в файлах конфигурации оболочки. В большинстве дистрибутивов Linux при запуске нового сеанса переменные среды считываются из следующих файлов:

    Глобальные файлы конфигурации оболочки, такие как /etc/environment и /etc/profile . Используйте этот файл, если хотите, чтобы новый каталог был добавлен всем пользователям системы $PATH .

    Файлы конфигурации для конкретной оболочки пользователя. Например, если вы используете Bash, вы можете установить $PATH в файле

    /.bashrc . Если вы используете Zsh, имя файла

    В этом примере мы установим переменную в файле

    /.bashrc . Откройте файл в текстовом редакторе и добавьте в конец следующую строку:

    Сохраните файл и загрузите новый $PATH в текущий сеанс оболочки с помощью source команды:

    Чтобы убедиться, что каталог был успешно добавлен, распечатайте значение вашего $PATH , набрав:

    Выводы

    Добавить новые каталоги к вашему пользователю или глобальной $PATH довольно просто. Это позволяет выполнять команды и сценарии, хранящиеся в нестандартных местах, без необходимости вводить полный путь к исполняемому файлу.

    Те же инструкции применимы для любого дистрибутива Linux, включая Ubuntu, CentOS, RHEL, Debian и Linux Mint.

    Не стесняйтесь оставлять комментарии, если у вас есть вопросы.

    Источник

    Читайте также:  Что такое код возврата exit code linux
    Оцените статью