- What is this $PATH in Linux and how to modify it
- How to change the path in the Linux terminal?
- Viewing PATH
- Method 1: Temporarily changing $PATH in terminal
- Method 2: Permanently changing $PATH in terminal
- Conclusion
- About the author
- Talha Saif Malik
- Переменная PATH в Linux
- Переменная PATH в Linux
- Выводы
- How to set your $PATH variable in Linux
- View your PATH
- Set your PATH
- Set your PATH permanently
What is this $PATH in Linux and how to modify it
Yes, you can change it — for example add to the $PATH folder with your custom scripts.
So: if your scripts are in /usr/local/myscripts to execute them you will have to type in a full path to the script: /usr/local/myscripts/myscript.sh After changing your $PATH variable you can just type in myscript.sh to execute script.
Here is an example of $PATH from RHEL:
To change your $PATH you have to either edit ~/.profile (or ~/.bash_profile ) for user or global $PATH setting in /etc/profile .
One of the consequences of having inaccurate $PATH variables is that shell will not be able to find and execute programs without a full $PATH .
Oh my God, you clarified it all for me by your statement —> «So: if your scripts are in /usr/local/myscripts to execute them you will have to type in a full path to the script: /usr/local/myscripts/myscript.sh After changing your $PATH variable you can just type in myscript.sh to execute script.» Thanks a lot
@ruggedbuteducated just bash commands which are executed after you log in. Please look into man bash and search for bashrc.
Firstly, you are correct in your statement of what $PATH does. If you were to break it somehow (as per your third point), you will have to manually type in /usr/bin/xyz if you want to run a program in /usr/bin from the terminal. Depending on how individual programs work, this might break some programs that invoke other ones, as they will expect to just be able to run ls or something.
So if you were to play around with $PATH, I would suggest saving it somewhere first. Use the command line instruction
echo $PATH > someRandomFile.txt
to save it in someRandomFile.txt
You can change $PATH using the export command. So
HOWEVER, this will completely replace $PATH with someNewPath. Since items in path are separated by a «:», you can add items to it (best not to remove, see above) by executing
The fact that it is an environmental variable means that programs can find out its value, ie it is something that is set about the environment that the program is running in. Other environmental variables include things like the current directory and the address of the current proxy.
How to change the path in the Linux terminal?
When you input a command into your Linux terminal, it does not search each directory to check any program with the same name. It only looks into the specified directories. The question that should come into your mind is how the terminal knows to look in the directories mentioned above? The answer to this question is straightforward. These directories are part of the $PATH environment variable, which the terminal uses to determine where to search. Any beginner Linux user should know how to change $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.
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.
Переменная 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, но только для текущего пользователя:
Выводы
В этой статье мы рассмотрели вопрос о том, зачем нужна переменная окружения PATH в Linux и как добавлять к её значению новые пути поиска исполняемых и связанных с ними файлов. Как видите, всё делается достаточно просто. Таким образом вы можете добавить столько папок для поиска и хранения исполняемых файлов, сколько вам требуется.
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.
How to set your $PATH variable in Linux
Telling your Linux shell where to look for executable files is easy, and something everyone should be able to do.
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.
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:
export PATH=$PATH:/place/with/the/file
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 ~/.bash_profile, ~/.bashrc, or ~/.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 ~/.kshrc, zsh uses ~/.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.