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

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

Читайте также:  1c linux xbase dbf

Выводы

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

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

Источник

How to add directory to system path in Linux

add directory to linux

Computer Hope

In Linux, the PATH environment variable stores the names of paths that will be searched for the executable files of any commands typed in the command line. The value of the PATH environment variable is a string containing several pathnames, each delimited by a colon. For instance, the default PATH on a typical system might look like this:

/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games

When you type a command such as cat and press Enter , the shell searches each of these directories for an executable file named cat. The first one it finds is the one it runs.

To view the current value of your PATH environment variable, you can use the echo command. As with all variables in the shell, when referring to the value you need to put a dollar sign before the variable name:

In the above example, the current value of path return you to the command prompt.

Setting PATH for your current shell session

You can set the value of PATH as you would any other shell variable, with the form NAME=VALUE, like this:

PATH=/my/first/path:my/second/path

The problem with this command is that it will completely overwrite the values you had before, which you probably don’t want. To add a new value in addition to the old ones. You can accomplish this by referring to PATH in the new definition, like this:

Using the command above adds your new path to the current value of PATH. Since the pathnames are searched in order, you probably want to add your new path at the end of the variable as we’ve done here. Instead, if you typed:

Your new path would be searched before, not after, the default system paths.

Using export to pass the PATH environment variable to child processes

This type of PATH definition sets the environment variable for your current shell session, but any new programs you run might not see the new path you’ve added. That’s because your shell lets you control the environment by requiring you to manually declare what environment variables are passed on to other programs and processes. You can accomplished this with the export command. If you run:

Any processes you run until you log out use the current value of PATH.

If you prefer, you can combine these two commands into a single line, for convenience. Put a semicolon between them so that the shell knows they’re separate commands:

PATH=$PATH:/my/new/path:/my/other/new/path;export PATH

If any of your pathnames have spaces in them, enclose the variable definition in quotation marks, to be safe.

PATH="$PATH:/putting/spaces in pathnames:/makes/life very/inconvenient";export PATH

Setting the PATH variable for every new shell session

The methods we’ve used so far only sets the environment variable for your current shell session; when you logout or close the terminal window, your changes will be forgotten. To set PATH to a certain value every time you log in or start a new shell session, add it to your bash startup script. Every time you start an interactive shell session, bash reads the following files in order (if they exist), and executes the commands inside of them:

/etc/profile ~/.bash_profile ~/.bash_login ~/.profile

The first file, /etc/profile, is the default startup script for every user on the system. One or more of the remaining three files are located in the home directory of every user. Any of those three can be used, but it’s important to know that they will be searched for in this order.

Читайте также:  Usr include linux version h

You can edit these files and manually change any lines containing PATH= definitions. Be careful if you do so, because these are the directories used to locate important operating system files.

To add a path for your current user only, you can leave the other PATH= lines untouched. Add a line like this to the end of the file:

PATH="$PATH:/new/path";export PATH

If you add this to the end of the .bash_profile file in your home directory, it takes effect every time your user starts a new shell session. If you add this to /etc/profile, it takes effect for every user on the system. Note that you need administrator privileges if you want to edit /etc/profile, so you can use sudo (or be logged in as root) to do so.

Источник

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.

Читайте также:  Php interpreter phpstorm linux

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

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.

Источник

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