Как добавить каталог в 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.
What the heck is my PATH, and how do I get it to do what I want?
When I was starting out, the whole concept of what the “PATH” was and what it did was way more confusing to me than it needed to be. For some reason I just didn’t come across a straightforwrard explanation for a long time (or wasn’t paying attention or understanding if I had…). Either way, after I got it, I was like “Why didn’t anyone just tell me this??”. If the “PATH” is still a nebulous concept for you, then you’ve come to the right place
The PATH demystified
As mentioned early in the Unix crash course, one of the easiest mistakes to make at the command line is to be trying to specify a file or program that isn’t where we think it is. For files, we usually point to where the file is using an absolute or relative path, where “path” here, in lowercase, just means a sort of address in the computer. But for programs that we use often, we usually want to be able to call them without having to provide the path to wherever the program is located. So a big part of getting specific programs to work properly at the command line is having them in a location on the computer that we can access no matter where we are.
The command line automatically checks in a list of pre-defined locations (directories) everytime we are trying to call a certain command. This is why we can use certain commands like ls and pwd and such from any directory we happen to be in. This list of pre-designated directories is stored in a special variable called “PATH” (all caps required). We can see our PATH, and which directories are stored in it, by entering echo $PATH at the command line (the $ is used to call variables in bash and other Unix languages; see the variables if new to this). Here’s a look at a rather messy one of mine:

This is a colon-delimited list of all the directories the command line looks in by default for programs on the particular computer I’m on right now. To make it a little friendlier to glance at, we can change the colons to newline characters by piping the output of echo $PATH into tr , one of our six glorious commands, to change the colons to newline characters for a more user-friendly output:

We can now more clearly see this is a list of directories. All of these places, stored in the variable called “PATH”, are searched whenever we are typing a command in the terminal window. If the command we are trying to use is present in any of the directories listed in our PATH, we don’t need to point at its specific location in full (its path, lowercase) when we are trying to use it – which is of course nice for things we use often.
To make a program available anywhere, we can either place that program in a directory that’s already in our PATH, or we can add a new directory to our PATH that contains the program. (Keep in mind that the order in which things appear in our PATH does matter. If we have two versions of a program with the same name, whichever shows up first will be the one that’s used.)
Adding a directory to our PATH
To demonstrate how to add a directory to our PATH, we’re going to create a new directory and within it make a quick bash script that tells us what time it is. We’re then going to add that directory to our PATH so that we can use the time-telling script from anywhere. If you want to follow along, you can make both by copying and pasting the following code block. If the following is confusing to you at first glance, running through the Unix crash course will get you almost entirely up to speed. For now, this is about the PATH though, so don’t worry too much about any minor details of this script – though a quick explanation follows

Ok great, so we just wrote a program that tells us what time it is according to our computer. That cat >> what-time-is-it.sh << ‘EOF’ line is say to put whatever we type that follows into that file we are just creating, up until we type “EOF”. Then for the little example script: #!/bin/bash tells the computer which program to use when executing the script; the current_time line is us setting a variable, called “current_time”, and storing within it the time that we use some unix magic to cut out of what the command date outputs; and then we are having it echo out the sentences (print to the terminal) and inserting the variable $current_time . Note the $ here is just calling the variable in the same way as when we did echo $PATH above. The last little part chmod +x what-time-is-it.sh is changing the properties of the file so that the computer knows it’s a program and will let us execute it more conveniently.
Let’s give it shot now. At the moment, the “what-time-is-it.sh” script is not in our PATH. It exists only in the directory we are sitting in, and that directory is not in the list of directories that pops up when we run echo $PATH . So right now, to execute the program, we need to tell the computer where it is with its relative or absolute path. Executing a file is different than doing something to it like we did with the cat command). And to execute a program, we need to be a bit more explicit even if it’s sitting in our current working directory. Here we’ll use the relative path, which looks like this:

And note, if we are not in this working directory that contains the script, we have to point to it in much the same way. Here, let’s move up one level and try again:

Now to make our program accessible to us wherever we are, without having to point at its location (its path, lowercase), we’re going to add its directory, my-bin , to the list of pre-specified directories in our PATH (the variable, all caps). To remove as much of our mortal enemy as possible from the process (human error), it’s easiest to just change into the directory we want to add, run pwd , and copy the absolute path:

Now that the absolute path of the directory is patiently waiting in the purgatory between copy and paste, we can modify our PATH to include it. This can be done temporarily or permanently, so let’s run through both here.
Temporarily
Running the following code modifies the PATH just for the current terminal session, so when we close the window it will be gone. Here is what mine looks like, we’ll break it down after looking at it:

Here, export is the command we are using, then we are specifying the variable we want to set, “PATH”. Then we are saying we want to set the “PATH” variable to include everything that is already in the PATH, by first putting $PATH , then we put a colon, which we saw above is what delimits the list of directories in the PATH variable, and then we added our new directory, /Users/Mike_Lee/my-bin in my case – that’s the part you would change to match yours. (The export part of this is a little more into the weeds than we need here, but basically it sets the variable for any sub-processes launched by the terminal.) Now if we look at my PATH like we did above, we see that at the end the directory /Users/Mike_Lee/my-bin is included!

Beautiful, and to see the benefits, we can now run our what-time-is-it.sh program without pointing to its location. Here is in the directory it sits (without needing to have the ./ like we needed above):

But we can also be anywhere else now:

Permanently
As noted above, that method only temporarily modifies our PATH, which is sometimes useful. But often we will want to modify it permanently. To do so we need to edit a sort of special file, there are a few of these, but that is a concept for another page. The one we are going to use here is called
/.bash_profile (files with a . in front of them are “hidden” files). This file either already exists in our home directory or we will create it if it doesn’t yet, and it gets run everytime we open a terminal window. This file and the others like it are what allow us to customize our terminal window with things like setting variables we always want, adding color schemes, or modifying our prompt. Here is one way we can permanently add a directory to our PATH by using echo to append the code to the end of that file:
NOTE
If we are working on a server or cluster, it may be the case that we actually want to modify our PATH varible in the
/.profile file instead of the
/.bash_profile file as done below. If you check your home location with ls -a
/.bash_profile , then change the two example lines below so that
/.profile is used in place of
Note that the code is exactly the same as we ran above, but now we’re appending it to the
/.bash_profile . And since this file gets run each time we open a terminal window, it’s the same thing as if we did it ourselves everytime we opened a terminal window – except much better of course because we don’t have to actually do it ourselves. Keep in mind that doing it this way, where we echo the text needed into the file, isn’t the only way to do this. The
/.bash_profile is just a text file, so we could open it with a regular text editor or a terminal-based one like nano and enter the same text that way. Also, since this file is run everytime we open a terminal session, it actually hasn’t been run yet since we just updated it right now, so our PATH variable hasn’t yet been updated to include the directory we just added. So we can either open a new terminal session, or we can run the source command on the
/.bash_profile file like this:
And that’s it! The PATH variable is just a special variable that contains all of the directories that are automatically searched when we try to call a program. Feel free to delete the what-time-is-it.sh script, but consider keeping the my-bin directory as a place to put things if you want them to be available from anywhere. Now that this directory is already in your PATH, you won’t have to worry about that part anymore and anything you put in there will be accessible from anywhere on that computer.
One last important note
We can add any directories to our PATH that we’d like, but we must be sure to always include the $PATH variable like that in the list as we edit it, otherwise we might get stuck with no regular commands working anymore (like ls , pwd , wc , etc.). If that happens, don’t despair! We can open that
/.bash_profile in any regular text editor (we may have to select “show hidden files” or something like that in the Finder window in order to see it), and then just delete whatever was added that messed things up. Then we’ll be able to launch a new terminal again that works just fine and try again!
Hoping to help level out the steep learning curve.
Have suggestions or ideas to improve anything here or add new content? Please feel free to post an issue
© 2023 Mike Lee. Powered by Jekyll, built off of the minima template and components of merenlab.org.
Beginner or expert, join the Microbialomics group and feel free to post questions or tips!
If you’ve found this site useful and think it is appropriate to do so, please consider citing the Happy Belly Bioinformatics paper
Переменная 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 и как добавлять к её значению новые пути поиска исполняемых и связанных с ними файлов. Как видите, всё делается достаточно просто. Таким образом вы можете добавить столько папок для поиска и хранения исполняемых файлов, сколько вам требуется.
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.
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.
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.