Path in linux terminal

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

Источник

Переменная PATH в Linux — просмотр и добавление

PATH представляет собой переменную среду особой важности. Без неё трудно представить операционную систему Linux такой же гибкой и безопасной, каковой она является для своих пользователей.

Давайте только представим, что произойдет с системой без этой важной переменной? Пользователю придется задавать в терминале полные пути ко всем интересующим его файлам. То есть, прописывать скрипт или команду в развернутом виде. Это отнимает кучу времени и сил, а также перегружает память человека.

Без PATH система не сможет разобраться, где именно искать требуемую программу с сопутствующими компонентами. В результате Linux просто не выдает нужного запроса, если путь не указан в терминале полностью. При наличии переменной данная проблема теряет свою актуальность.

Как посмотреть содержимое PATH

Для этих целей есть команда echo. Пользователю остается вооружиться ею для получения нужной информации. Что нужно прописать в терминале:

В окне появится список каталогов, которые разделены знаком двоеточия. А теперь добавим пару слов о том, как система обнаруживает путь к определенной папке. Линукс реагирует на запуск конкретной программы, после чего начинается поиск исполняемого файла по имени.

Читайте также:  Работа с сигналами linux

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

Добавление нового пути

Для добавления нового пути к переменной существует команда export.

ВАЖНО! Актуальное значение не должно быть переписано полностью. Необходимо лишь дописать новое значение к старой формулировке.

Чтобы разделить оба значения, ставится знак двоеточия.

С помощью export, добавим в path новый путь «/usr/newpath».

В текущем сеансе операционная система без проблем отреагирует на внесенные пользователем коррективы. Но есть один важный нюанс, о котором нельзя умолчать. Новые настройки потеряют свою актуальность после первой же перезагрузки устройства. Если новое значение потребуется юзеру на постоянной основе, ему следует закрепить его в конфигурационном системном файле.

В некоторых дистрибутивах значение переменной можно найти в файле /etc/environment.

Далее следует дописать нужное значение вручную (не заменить, а именно добавить). Еще раз напоминаем о важности соблюдения данного правила. В ином случае система не сможет нормально функционировать – у пользователя начнутся разного рода неприятности.

Чтобы выполнить добавление значение в переменную PATH для конкретного пользователя системы, можно не изобретать велосипед, а поступить гораздо проще:

Как уже говорилось ранее, переменная PATH служит надежной защитой для операционной системы Linux. Однако пользователи нередко практикуют еще один способ того, как уберечь персональный компьютер. Каким образом это происходит? Это можно сделать посредством создания локальной папки bin.

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

Заключение

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

Дополнительная информация для владельцев дистрибутива Линукс: пользователь не имеет никаких ограничений в вопросе добавления каталогов в переменную PATH для поиска и хранения исполняемых файлов (имеется в виду их допустимое количество). Можно добавлять столько папок, сколько нужно.

Источник

How to change the path in the Linux terminal?

Viewing PATH

Suppose you want to install programs in a different location on your system and run the program without mentioning their location. A simple way to accomplish this is to change your $PATH variable. Write out the following command to view what exists currently in your $PATH:

Most likely, you will see the various directories separated by colons. Now let’s check out the methods of changing the $PATH in the Linux terminal.

Method 1: Temporarily changing $PATH in terminal

For instance, you have a directory named “bin” in your Home directory, and you want this location to be where you save all of your shell scripts. You can easily make these changes by modifying the $PATH variable. The modified $PATH variable will be exported to the shell child process environments using the “export” command. In addition, after modifying the $PATH, you can now execute any shell script by only specifying the executable script name rather than typing the entire path of the file. These settings will change the $PATH, but temporarily.

echo” the $PATH variable to confirm the changes we made into the path of the Linux terminal.

Method 2: Permanently changing $PATH in terminal

To change the $PATH permanently, you must define the $PATH variable configuration files. When you start a new session in most Linux versions, environment variables are read from the shell configuration files customized for each user. If you are a bash user, utilize the “

./bashrc” file for changing $PATH. First, open the “

./bashrc” file in the text editor by typing the following command.

Write out the below-given lines into this configuration file.

Execute the source command to save the file with the change we made into the $PATH. This command will also load the new path in the current session of the Linux terminal.

Again, print out the value of $PATH for the confirmation of the changes.

The output declares that the $PATH is successfully changed in the Linux terminal.

Читайте также:  Parom tv linux �� ��������

Conclusion

Changing $PATH in the terminal comprises a simple yet straightforward procedure. This allows any Linux user to run scripts and commands from a non-standard location without specifying the entire path of those executable shell scripts. This article has provided you two different methods for changing $PATH in the Linux terminal.

About the author

Talha Saif Malik

Talha is a contributor at Linux Hint with a vision to bring value and do useful things for the world. He loves to read, write and speak about Linux, Data, Computers and Technology.

Источник

How to Permanently Set $PATH in Linux

Understanding the $PATH Variable

In this tutorial, we will show you how to permanently set your PATH on Linux.

First off, why should you care?

The $PATH variable, or just PATH, without the $ indicating variables, specifies a list of directories that impacts your computing platform’s functionality in a critical way. This is because the $PATH is the list of directories in which the system searches for executable programs, scripts, or files.

Imagine trying to run the ssh command, for example, to connect to a server. What happens if the system cannot find the ssh program? You are unable to connect to servers and run computations. You have a plethora of useful programs, examples like python , javac , npm , make , chmod , apt-get and so on, that your computer needs to be able to find when you invoke them at the command line.

The $PATH variable is the key that makes it possible to find the correct program and execute it at your command without needing the executable’s full directory path. When your PATH is set incorrectly, your shell will be unable to find programs, and certain commands will fail.

Using bash_profile to Set your PATH

A common mistake with the $PATH variable is to set it in the current shell only, without persisting the change. When you open a new shell, the changes are lost, and you are once again unable to execute certain commands because those programs are not found in the PATH.

The first way of setting your $PATH permanently is to modify the $PATH variable in your Bash profile file, located at /home/ /.bash_profile .

For example, let’s say I want to add a new directory /home/tomahawk/tools/jdk1.8.0_92/bin to my PATH. You might recognize this as a Java Development Kit installation. However, that is beside the point. Whatever the directory contains, I can add it to our path and make the programs that this bin directory contains accessible from the command line by adding the following line to the end of the file

A good way to edit the file is to use nano , vi , vim or emacs . You can use the command sudo

/.bash_profile , and enter your admin password when prompted, then add that line to the end and save the file.

To activate the changes in the current shell, you have to «source» the updated bash_profile file. You do this with the command:

This simply imports the file’s settings into the current shell. Now every time you open your shell, your bash_profile will automatically be «sourced» and you won’t need to run this command every time.

Now we can invoke commands or programs in the new directory /home/tomahawk/tools/jdk1.8.0_92/bin , such as javac , located at /home/tomahawk/tools/jdk1.8.0_92/bin/javac by just typing at the command prompt the name of the program. We can do this now from any directory, because the PATH has been updated to look for executable programs in our new directory.

Now runs the correct javac program, printing out something like the following:

bash_profile is appropriate when you want to set a PATH variable customized for a single user of the system. If you wanted to set PATH for all users of a system, there are better ways to do so, which we cover further on in this guide.

Using bashrc to Set your PATH

Instead of setting the PATH in

/.bash_profile , we can also add the directories we want to the PATH in

/.bashrc instead. Setting the PATH in bashrc looks identical to how we set it in bash_profile .

For example, to include the directory /home/tomahawk/.rbenv/bin in my path, I edit or create the file /home/tomahawk/.bashrc , adding the following line:

Notice that, like last time, the first thing in our new PATH export is the inclusion of the existing $PATH variable. This ensures that we preserve the current value of PATH, and just add any additional directories on to the PATH, after the $PATH variable. If you do not do this, you will overwrite the PATH variable entirely, and miss critical directories the system needs to be on the PATH. As a result, your system can become unusable.

Читайте также:  Темы мас для windows

The difference between using bashrc and bash_profile is that bash_profile is used for login shells. These run when you login via the console, or log in using ssh . In contrast, once you are logged in, and you open a command shell or run the bash command, the bashrc file will run. Your PATH settings from bashrc will then be available.

The effect of setting the PATH is similar. In addition, we must activate any changes in the bashrc file into the current shell the first time we make this change, just as we did for the bash_profile file. This time, we run source

/.bashrc . We can now access the new PATH at the command line. It has been set permanently and will stay the same between multiple logins into the system.

Using a Profile File to Set your PATH

We can also set the PATH permanently using a user’s profile file. This is different from

/.bash_profile in that it is set not for shells only, but for all programs.

User profiles are loaded at login. The PATH variable can be set in the

To set my PATH to include everything already in $PATH, as well as a new directory /home/tomahawk/.exenv/bin , I edit the file at

/.profile and set the PATH as follows

As in all prior examples, we will need to source these changes to make them active for the current shell, but subsequent logins will persist the changes.

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Once that’s done, I can run the exenv command, which is one of the programs available in the folder I just added to the PATH, and I get back the output of my exenv version:

You can read more about the exenv program here, but you can use this process to set PATH permanently to include any program or directory you want.

Permanently Setting your PATH for Other Shells like ZSH and KSH

If you use alternative shells such as zsh, ksh and others, you can set the PATH permanently using those shells’ configuration.

Like bash, both zsh and ksh use a zshrc and khsrc file, respectively, to set the path for non-login shells. For login shells, they use the analogous shell profile files zprofile and kprofile.

You can therefore set the PATH permanently for these shells in a similar way to what we did for Bash. For zsh, you can find these files, or create them if they do not exist, at

Similarly, you can set PATH permanently for ksh in the configuration files located at

There are plenty of other shells you can use, such as the C Shell and the tcsh shell. Setting the PATH permanently for them will generally follow the pattern we have seen here.

Permanently Setting System-Wide PATH for all Users

System-wide settings for all users can be set in /etc/profile . There is considerable flexibility and multiple options for setting the PATH permanently system-wide.

Your Linux system will execute all script files ending in .sh in /etc/profile.d whenever a bash shell is entered, as well as when the desktop session loads.

You can therefore add a new file, such as env.sh inside the directory /etc/profile.d . In this file, we can export the PATH variable, setting it permanently to our choice of path directories, for example:

Files in /etc/profile.d are sourced by /etc/profile, thus activating our system-wide PATH whenever a user logs in.

We can also set PATH for all users in /etc/environment , which takes key-value pairs of the form:

Troubleshooting PATH Problems

As we saw, setting the PATH permanently in Linux has many options. You can set the PATH for only a certain user, for all users, or for only certain types of command shells. However, it’s a good idea to not fiddle with system-wide PATH settings unless you really know what you are doing.

If you encounter problems, a good starting point is to find out the current value of $PATH, by running the command:

For more troubleshooting tips, check out this resource.

Источник

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