- Переменная PATH в Linux
- Переменная PATH в Linux
- Выводы
- How to set your $PATH variable in Linux
- View your PATH
- Set your PATH
- Set your PATH permanently
- How Does PATH Work in Bash
- Environment variable and $PATH
- Modifying PATH
- Adding directory to PATH
- Removing directory from PATH
- Final thoughts
- About the author
- Sidratul Muntaha
Переменная 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 set your $PATH variable in Linux
Thomas Hendele on Pixabay (CC0). Modified by Opensource.com. CC BY-SA 4.0.
Being able to edit your $PATH is an important skill for any beginning POSIX user, whether you use Linux, BSD, or macOS.
When you type a command into the command prompt in Linux, or in other Linux-like operating systems, all you’re doing is telling it to run a program. Even simple commands, like ls, mkdir, rm, and others are just small programs that usually live inside a directory on your computer called /usr/bin. There are other places on your system that commonly hold executable programs as well; some common ones include /usr/local/bin, /usr/local/sbin, and /usr/sbin. Which programs live where, and why, is beyond the scope of this article, but know that an executable program can live practically anywhere on your computer: it doesn’t have to be limited to one of these directories.
More Linux resources
When you type a command into your Linux shell, it doesn’t look in every directory to see if there’s a program by that name. It only looks to the ones you specify. How does it know to look in the directories mentioned above? It’s simple: They are a part of an environment variable, called $PATH, which your shell checks in order to know where to look.
View your PATH
Sometimes, you may wish to install programs into other locations on your computer, but be able to execute them easily without specifying their exact location. You can do this easily by adding a directory to your $PATH. To see what’s in your $PATH right now, type this into a terminal:
You’ll probably see the directories mentioned above, as well as perhaps some others, and they are all separated by colons. Now let’s add another directory to the list.
Set your PATH
Let’s say you wrote a little shell script called hello.sh and have it located in a directory called /place/with/the/file. This script provides some useful function to all of the files in your current directory, that you’d like to be able to execute no matter what directory you’re in.
Simply add /place/with/the/file to the $PATH variable with the following command:
You should now be able to execute the script anywhere on your system by just typing in its name, without having to include the full path as you type it.
Set your PATH permanently
But what happens if you restart your computer or create a new terminal instance? Your addition to the path is gone! This is by design. The variable $PATH is set by your shell every time it launches, but you can set it so that it always includes your new path with every new shell you open. The exact way to do this depends on which shell you’re running.
Not sure which shell you’re running? If you’re using pretty much any common Linux distribution, and haven’t changed the defaults, chances are you’re running Bash. But you can confirm this with a simple command:
That’s the «echo» command followed by a dollar sign ($) and a zero. $0 represents the zeroth segment of a command (in the command echo $0, the word «echo» therefore maps to $1), or in other words, the thing running your command. Usually this is the Bash shell, although there are others, including Dash, Zsh, Tcsh, Ksh, and Fish.
For Bash, you simply need to add the line from above, export PATH=$PATH:/place/with/the/file, to the appropriate file that will be read when your shell launches. There are a few different places where you could conceivably set the variable name: potentially in a file called
/.profile. The difference between these files is (primarily) when they get read by the shell. If you’re not sure where to put it,
/.bashrc is a good choice.
For other shells, you’ll want to find the appropriate place to set a configuration at start time; ksh configuration is typically found in
/.zshrc. Check your shell’s documentation to find what file it uses.
This is a simple answer, and there are more quirks and details worth learning. Like most everything in Linux, there is more than one way to do things, and you may find other answers which better meet the needs of your situation or the peculiarities of your Linux distribution. Happy hacking, and good luck, wherever your $PATH may take you.
This article was originally published in June 2017 and has been updated with additional information by the editor.
How Does PATH Work in Bash
Here come the environment variables into play, especially the PATH variable. This variable is responsible for telling bash where to look for those programs. Let’s check out how PATH works and how to view/modify PATH.
Environment variable and $PATH
In the shell terminology, the “environment” is an area that the shell builds every time it starts a session. To manage the environment, there are “environment variables” denoting different parts of the environment. The value of the variable can be string, directory location, value or others.
PATH is such an environment variable that keeps track of certain directories. By default, the PATH variable contains the following locations.
- /usr/bin
- /usr/sbin
- /usr/local/bin
- /usr/local/sbin
- /bin
- /sbin
- /snap/bin (if Snap is installed)
Want to see what directories are currently registered under PATH? Fire up a terminal and run the following command.
Here, the $ sign is to denote a variable. The echo command prints the value of the PATH variable.
Now, why this specific environment variable is so important? It’s because how shell and the system as a whole treats it. The PATH variable stores where executables may be found. Whenever any command is run, the shell looks up the PATH directories for the target executable file and runs it.
For example, let’s test with the echo command. Here, I’m running an echo command.
Where’s the executable file of echo? Run the next command to find out.
As we can see, the echo executable is located at /usr/bin/echo. Where’s which located? Let’s find out.
It’s also located at /usr/bin/which. Most of the command tools are located under the /usr/bin directory. Here, bash is consulting PATH for the locations to search for the executable(s) of a command.
Modifying PATH
Before we modify the value of PATH, it’s important to understand its structure. Run the command again to check the value of PATH.
Notice that each of the directories is separated by a “:” sign.
Adding directory to PATH
To add a custom directory to PATH, we’ll be taking the help of the bashrc file. It’s a special bash script that bash loads every time a new bash session starts. Note that the bashrc file is unique to every single user in the Linux system.
Open the bashrc file in a text editor. If the bashrc file isn’t present already, then the editor will create it automatically.
Here, it’s the default bashrc that comes with Ubuntu. Go to the last of the file (if it exists) and add the following line.
Here, the new value of PATH variable will be the old variable along with the new directory we just added.
Save the file and tell bash to reload it.
Let’s verify whether the new path was successfully added.
Voila! PATH updated successfully! Now, bash will also search the new path for executable(s). I already have a script demo.sh on desktop. Let’s see if bash can call it without specifying the exact location.
Yup, bash can directly call it without any problem.
Removing directory from PATH
There’s no straightforward way of adding/removing directories from PATH. Let me explain.
The value of PATH is actually fixed. Then, what about the bashrc trick? Bashrc is a bash script that bash loads every time it starts a session. In bashrc, we just declared that the new value of PATH will be its default value and the user-defined directory. Now, every time bash loads, it sees that bashrc is telling to assign a new value of PATH and that’s what it does.
Similarly, if we want to remove a directory from PATH, we have to re-assign a different value of PATH in the bashrc so that every time bash starts, it uses the modified value.
Let’s have a look at this example. I’m willing to remove the directory “
/Desktop” from the PATH.
If the directory would be /home/wrong/dir, the command would look like this.
Here, the interesting part is the sed tool. Learn more about sed here and here. Long story short, using sed, we’re modifying the output of the echo command. Now, we can use this modified output to change the value of PATH.
Open bashrc in a text editor and add the following lines. I’m intentionally keeping the previous lines to prove that it’s working.
Alternatively, you can also manually set the value of PATH. It’s a laboring process but more straightforward and simple.
Here, the value of the command will be assigned to PATH. Save the file and reload bashrc.
Let’s verify the result.
The PATH value is updated!
Final thoughts
In bash, the PATH variable is an important one. Any program that runs through the bash session inherits the variable, so it’s important that PATH includes the necessary directories only. Adding more directory will only add redundancy to the system.
To see all the environment variables for bash, run this command. The first command part will return all the environment variables and the second part will sort the output in ascending order.
Want to spice up your bash experience? Bash aliases offer a unique way of speeding and spicing things up. Learn more about bash aliases.
About the author
Sidratul Muntaha
Student of CSE. I love Linux and playing with tech and gadgets. I use both Ubuntu and Linux Mint.