Configure path in linux

How to Permanently Set $PATH in Linux

Unlocking the full potential of your Linux system involves understanding the importance of the $PATH variable, which serves as a roadmap for your operating system to locate and execute commands swiftly and effortlessly. However, if you find yourself repeatedly setting the $PATH every time you log in or reboot, it is time to learn how to permanently configure it.

In this comprehensive guide, we will walk you through the step-by-step process of setting the $PATH variable in Linux, ensuring that your customizations persist across sessions.

What is a $PATH Variable in Linux

The $PATH variable is a fundamental part of the Linux operating system, acting as a reference to locate executable files. It consists of a list of directories separated by colons (:) , with the system searching for commands in these directories when they are executed. Understanding the importance of the $PATH variable is crucial to effectively manage your command-line experience.

There are multiple approaches to permanently setting the $PATH variable in Linux and the two most common methods involve:

Each method has its advantages and disadvantages, so choose the one that best suits your needs. The PATH variable can also be set on a per-user basis or system-wide for all user accounts.

Check $PATH Variables in Linux

You can see your $PATH variables by running the following echo command:

Check $PATH Variable in Linux

Add a Directory to PATH Variable Linux

To temporarily add a directory, for example, /opt/sysadmin/scripts to your path, you can run the following command:

$ PATH=$PATH:/opt/sysadmin/scripts $ echo $PATH

Add Directory to PATH in Linux

One way to permanently set the $PATH variable is by modifying shell configuration files, such as .bashrc or .bash_profile . These files are executed each time you start a new shell session.

$ nano ~/.bashrc OR $ vim ~/.bashrc

The .bashrc File in Linux

Locate the line that begins with «export PATH attachment_8239″ aria-describedby=»caption-attachment-8239″ style=»width: 831px» > The .bashrc File in Linux

If you are unable to find this line, you can add it manually inside the file at the bottom of the page. As an example, I am adding the /opt/sysadmin/scripts directory path to my PATH using the command given below:

export PATH="$PATH: /opt/sysadmin/scripts"

Permanently Add Directory to PATH in Linux

To apply the changes, either open a new terminal or run the following command:

Note: The above method only works for user accounts.

Permanently Set $PATH for All Users

To permanently set system PATH for all users on the system, append the following lines at the end of the /etc/profile file. On some Linux distros, you can also use the /etc/bash.bashrc file (if it exists) but it should be sourced in /etc/profile for changes in it to work.

PATH="$PATH:/opt/sysadmin/scripts" export $PATH OR $export PATH="$PATH:/opt/sysadmin/scripts"

Alternatively, instead of making changes directly in the /etc/profile (which is not recommended), you can create a script (ending with the .sh extension) under the directory /etc/profile.d (if it exists) and make the changes in that script.

$ sudo vim /etc/profile.d/set_system_path.sh

Append the following line in it:

export PATH="$PATH:/opt/sysadmin/scripts"

Next, source the ~/.bashrc or /etc/profile or /etc/bash.bashrc (depending on the one you used), for the changes to take effect.

$ source ~/.bashrc OR $ source /etc/profile OR $ source /etc/bash.bashrc

Then confirm that your PATH has been set correctly:

$ echo $PATH /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/opt/sysadmin/scripts:/opt/sysadmin/scripts

Set PATH Variable in /etc/environment File

Another approach to permanently setting the $PATH a variable is by using environment-specific files. Two common files used for this purpose are /etc/environment and /etc/profile.d/.

Читайте также:  Ping linux как установить

Next, locate the line that begins with «PATH /opt/sysadmin/scripts:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/>

To apply the changes, reboot your system or run the following command:

After making modifications to the $PATH variable, it’s crucial to verify that the changes have taken effect.

Check PATH in Linux

This will display the updated $PATH variable, including the directories you added. Ensure that the desired directories are now part of the $PATH variable.

Conclusion

To make the most of your Linux system, it’s a must for you to understand the $PATH variable that acts like a map and helps your computer find and run commands quickly.

If you are tired of setting $PATH every time you log in or restart your computer, better to set it permanently using the step-by-step guidelines presented in the above article.

If you have managed to do this process, you will have a better command-line experience on your Linux system.

Источник

Переменная 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 новым, нужно именно добавить (дописать) это новое значение к уже имеющемуся, не забыв о разделителе-двоеточии:

Читайте также:  Sticky bit astra linux

Теперь мы можем убедиться, что в переменной PATH содержится также и имя этой, добавленной нами, папки:

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

В ОС Ubuntu значение переменной PATH содержится в файле /etc/environment, в некоторых других дистрибутивах её также можно найти и в файле /etc/profile. Вы можете открыть файл /etc/environment и вручную дописать туда нужное значение:

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

Выводы

В этой статье мы рассмотрели вопрос о том, зачем нужна переменная окружения PATH в Linux и как добавлять к её значению новые пути поиска исполняемых и связанных с ними файлов. Как видите, всё делается достаточно просто. Таким образом вы можете добавить столько папок для поиска и хранения исполняемых файлов, сколько вам требуется.

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

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. This way:

If there are already some paths added, e.g. PATH=$PATH:$HOME/.local/bin:$HOME/bin , another can be added by separating with a : e.g. PATH=$PATH:$HOME/.local/bin:$HOME/bin:/home/ec2-user/pear/bin .

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/bin:~/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 ~/.profile , or in ~/.bash_profile or if that’s what you have. (If your login shell is zsh and not bash, put it in ~/.zprofile instead.)

Читайте также:  Smart tv linux sony

The profile file is read by login shells, so it will only take effect the next time you log in. (Some systems configure terminals to read a login shell; in that case you can start a new terminal window, but the setting will take effect only for programs started via a terminal, and how to set PATH for all programs depends on the system.)

Note that ~/.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 ~/.profile (or ~/.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 ).

if [ -z "$" ]; then export PATH=/usr/local/bin:/usr/bin:/bin; fi 

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.

Источник

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