How to add to the path in 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 to add directory to system path in Linux

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 a series of pathnames, each delimited by a colon. For instance, the default PATH on a typical system might look like this:

Читайте также:  Windows 10 не запрашивать пароль после отключения экрана

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:

The problem with this command is that it will completely overwrite the values you had before, which you probably don’t want. If you 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:

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

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. If you want 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:

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.

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.

If you want 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:

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.

Читайте также:  Дата создания файла windows при копировании

Источник

How to Add a Directory to PATH in Linux [Quick Tip]

The PATH variable in Linux stores the path to the directories where it should look for executables when you run a command.

As you can see, the PATH consists of several directories (like /usr/local/sbin, /usr/bin and more) separated by colon (:).

If you want to run some executables as command from anywhere in the system, you should add their location in the PATH variable.

This is common while setting up a development environment. For example, imagine you downloaded and installed Java and Maven. To make your programs work properly, you’ll need to specify the location of the binaries of Maven and Java in the PATH.

This quick tutorial is about setting up PATH in Linux. Apart from the steps, I’ll also mention things you should be careful about while dealing with PATH.

Adding a directory to PATH in Linux

The process to add a new directory to the PATH variable in Linux is essentially this:

Where your_directory is the absolute path to the concerned directory.

Let’s say, you download and extracted Maven to the home directory and you want to add its bin directory to the PATH. Let’s assume that the absolute path of this bin directory is /home/abhishek/maven/apache-maven-3.8.0/bin.

Here’s what you should be doing:

Things to pay attention here:

  • The $ before a variable name means you are referring to its value. PATH is the variable name, $PATH is the value of variable PATH.
  • You should not use $ with PATH on the left side of =
  • There must not be any spaces before and after =
  • Don’t forget to include the : after $PATH because the directories in the PATH are separated by colon.
  • There must not be a space before and after the colon (:).

Once you have set the PATH with the new value, please check that the PATH has been correctly updated.

You may want to run the command or script for which you modified the PATH. This will tell you for sure if the PATH is correctly set now.

Making the changes to PATH permanent

You added the desired directory to the PATH variable but the change is temporary. If you exit the terminal, exit the session or logout from the system, the PATH will revert and the changes will be lost.

If you want to make the changes to the PATH variable permanent for yourself, you can add it to the .bashrc file in your home directory, assuming you are using the Bash shell.

You can use a text editor like Nano or Vim for this task.

If you want the modified PATH variable to be available for everyone on the Linux system, you can add the export to the /etc/profile file. This is suitable when you are a sysadmin and have a configured system with custom path.

Bonus tip: The directories take precedence in PATH

There are several directories in the PATH variable. When you run an executable file/command, your system looks into the directories in the same order as they are mentioned in the PATH variable.

If /usr/local/sbin comes before /usr/bin, the executable is searched first in /usr/local/sbin. If the executable is found, the search ends and the executable is executed.

Читайте также:  Windows 10 отключение синхронизации файлов

This is why you’ll find some examples where the additional directory is added before everything else in PATH:

If you think that your additional directory should be searched before everything else you should add it before the $PATH otherwise add it after $PATH.

Was it clear enough?

I have tried to explain things with necessary details but not going too deep into details. Doe sit make the topic clear or are you more confused than before? If you still have doubts, please let me know in the comments.

Like what you read? Please share it with others.

Источник

Как добавить каталог в 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.

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

Источник

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