Adding bin to path linux

Переменная 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

I have a systemd service which calls a PHP script that creates a tmux session on boot.

Globally I have the most current tmux for the distro (V>=2.5).
The script’s USER has a $HOME/bin/tmux of 2.0

What I need is for this systemd to use the tmux binary in the user’s $HOME.
I have set the USER & GROUP variables in the systemd service file but it seems to call the globally installed binary.

Is it possible to explicitly set the binary that should be called for this service invocation?

If possible I’d rather not start to hardcode the path in the PHP file itself.

4 Answers 4

You could hardcode the PATH in the systemd service:

More flexible would be PAM. It’s awfully roundabout compared to simply using bash -c ‘. ‘ , but you can do this with PAM.

Create a new PAM configuration in /etc/pam.d (say /etc/pam.d/foo ) and add:

And in /home/someUser/some-file , add:

Of course, you can adjust the some-file name to something more sensible, but the path in user_envfile has to be relative to the user’s home directory (the user that you set in User= in the service).

Then in the service file, in the [Service] section, add ( foo being the file in /etc/pam.d created earlier):

Читайте также:  Windows 10 не видит динамики монитора

Now, when you start the service (after reloading, etc.), the session modules in /etc/pam.d/foo will be run, which in this case is just pam_env . pam_env will load environment variables from /etc/environment , subject to constraints in /etc/security/pam_env.conf , and then the user environment from

/some-file . Since PATH is set to a default value in /etc/environment , the user environment prepends to this default value.

Here, the default value of user_envfile is .pam_environment , which is also read by the PAM configuration of other things like SSH or LightDM login, etc. I used a different file here in case you don’t want to affect these things. You could remove the user_envfile=. and use the default

/.pam_environment . you could also just use an existing PAM configuration in /etc/pam.d which has user_readenv=1 , but other PAM modules may cause unwanted side effects.

I know I’m digging up a slightly dated post, but I too was trying to figure out how I could get the PATH/environment variables configured so thaty I could get the scheduler to run automatically when the server is running.

I did find a solution that works for me on Ubuntu 18.04 and 18.10

I provided a full write-up of how to install Airflow and PostgreSQL on the backend on the link here.

**from the later part of my article Essentially it comes down to making a specific change to the airflow-scheduler.system file.

This is one of the ‘gotchas’ for an implementation on Ubuntu. The dev team that created Airflow designed it to run on a different distribution of linux and therefore there is a small (but critical) change that needs to be made so that Airflow will automatically run when the server is on. The default systemd service files initially look like this:

However, this will not work as the ‘EnvironmentFile’ protocol doesn’t fly on Ubuntu 18. Instead, comment out that line and add in :

You will likely want to create a systemd service file at least for the Airflow Scheduler and also probably the Webserver if you want the UI to launch automatically as well. Indeed we do want both in this implementation, so we will be creating two files, airflow-scheduler.service & airflow-webserver.service. Both of which will be copied to the /etc/systemd/system folder. These are as follows:

airflow-scheduler.service

airflow-webserver.service

Finally, with both of those files copied to the /etc/systemd/systemd folder by way of a superuser copy command sudo cp it is time to hit the ignition:

sudo systemctl enable airflow-scheduler sudo systemctl start airflow-scheduler sudo systemctl enable airflow-webserver sudo systemctl start airflow-webserver

Источник

How can I add

I’m just trying to follow this tutorial and set up my environment. My system is WSL Ubuntu 18.04. Here is already an answer on my question, but I as an absolute novice in Linux/UNIX don’t know which variant presented there more suitable for my goal. Do I need to add this string

Or may I need to accomplish the second step from the answer?

And then run these commands?

2 Answers 2

/bin folder in your home folder, it’ll already be in your default path. No need to modify anything, or add folders to a hidden .local folder. Create the

/bin folder, log out, log back in, and open a terminal window, and you can confirm the path by typing echo $PATH .

Update #1:

If you decide to use

/.local/bin anyway, add this to the end of your

Then log out, log back in, and your new path will be available.

/.local/bin But now only

/.local This command — export PYTHONUSERBASE=/myappenv solve the problem, but only till reload.

expanded to the absolute path to your home directory) so you’ll need to add

/.local/bin to your PATH. You can set your PATH permanently by modifying

/.profile. I’m trying to follow these instructions. And accordingly it is not as simple as adding /bin in my home directory.

The PATH variable gets changed when this shell command is executed:

/.profile will be executed automatically when you open a bash session (normally when you open a new terminal window/tab).

So if you want to change the PATH in current shell session only, you could just type export PATH=xxx and execute it once. But if you want to make it difference permanently, you should add the command above into

Источник

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.

Читайте также:  Отформатировать флешку через консоль linux

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=

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

    Читайте также:  Настройка f lux для windows

    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.

    Источник

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