Edit path file in linux

Is there a GUI to edit the PATH variable?

There’s a GUI in Windows to edit the path variable. I was wondering if there’s something equivalent in Ubuntu to do the same.

There’s no GUI available for the purpose. But its quite easy to do it the Command-line way. To read and understand fully about environment variables, checkout the official documentation regarding it- https://help.ubuntu.com/community/EnvironmentVariables

1 Answer 1

Thing is. path is set inside several text files based on what you want to accomplish, like in ~/.profile for the user, /etc/profile as a default for users, /etc/environment for the system or /etc/bash.bashrc for system wide interactive bash shells. In some of these $PATH is set as part of some coding.

So a text editor is the most logical thing to use. Like gedit if you want it graphical but you will still be looking at the same type of deal as with nano or vi from commandline. But it will not be possible with something where you edit in some directories with an input box to browse directories since in Linux PATH can have some more logic to it than simply editing a variable.

My advice: get used to command line editing for things like this and similar things. It will one day help you fix your problems when not being able to login or Unity crashing just after login.

There is more likely to be a reason for it being done this way. Linux has many more ways of doing things then either of us will ever use but that does not mean someone else does not need them.

For Latex I would suggest adding it to /etc/bash.bashrc . That is the place to edit path for system wide bash shells.

Читайте также:  Безопасность защищенность от вирусов linux

After adding it in and saving you can check with

if it is set correctly (and this will be permament).

Источник

Переменная 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.

Источник

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 .

Читайте также:  Linux sudo access user

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.

Источник

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