Linux как редактировать path

How do I modify my PATH so that the changes are available in every Terminal session

I want to add a directory to search my search path. I know I have to modify the PATH environment variable. However, I want the change to be permanent, so that it is always in effect, for every Terminal (bash) window I open. There is an overload of confusing and possibly conflicting information in https://help.ubuntu.com/community/EnvironmentVariables I am using Ubuntu 10.04. Suppose I want to add /usr/local/foo to my PATH . Which file ( .bashrc , .profile , .bash_login , etc. ) should I modify and what should the new line(s) look like?

10 Answers 10

The following command adds a path to your current path:

export PATH=$PATH:/my/custom/path 

If you want your setup to execute this command every time, there are a number of places where you can put it. When you login, the following scripts will be executed in this order:

/etc/profile (which starts by loading everything in /etc/profile.d) ~/.profile (which starts by loading ~/.bashrc if you are running bash) 
  • ~/.profile is only loaded if ~/.bash_profile and ~/.bash_login DO NOT EXIST. Otherwise, at least bash, will load them instead. It is advisable to use .profile and not the bash specific scripts. So, if in these attempts you created .bash_login , please delete it now.
  • ~/.bashrc is only loaded if you are running an interactive session. (something with a prompt where you can actually type something).
  • ~/.bashrc is loaded again and again, every time you open up a new terminal. So a new tab in gnome-terminal, a new virtual terminal, etc. So even if you don’t login again, .bashrc is loaded (and thereby resets its environment) every time you open a new shell.
  • Things like byobu should really go into .profile , (otherwise it won’t work 😉
  • Things like paths should go into .profile if you want them to work outside of the interactive sessions. (say when you press Alt + F2 in GNOME)

I’ll mark this as the answer if you update it to include the requested export line that should be added to .profile.

This used to be valid only for console logins (e.g. ssh, or the virtual terminals accessible for Ctrl+Alt+Fx). I didn’t know that /etc/gdm/Xsession sources ~/.profile these days. Neat!

to make this answer more comprehensive please add MattH’s comment about sourcing ~/.profile to activate changes without a logoff/on cycle.

@JoshuaFlanagan: export is not necessary for PATH . PATH is already an environment variable (as opposed to a shell variable)

@schwiz: ~/.profile is not executed on each terminal, it is executed before, when your desktop session starts. The one executed on every terminal is ~/.bashrc

I got it to work by modifying ~/.profile

It looks like adding ~/bin to my path was a bad example, as there is already code in ~/.profile to do that automatically, if the directory exists.

To add the usr/local/foo directory to my path for every session going forward, I add/edit the following line at the end of my .profile:

export PATH=$PATH:/usr/local/foo 

However, to make this take effect, I needed to log out and log back in (simply closing the Terminal window and opening a new one did NOT work).

Читайте также:  Установка принтера kyocera astra linux

Make that export PATH=»$PATH:/usr/foo» , in case you ever have spaces or other special characters in $PATH .

@MattH: no you can’t. if you source ~/.profile in a given terminal, it will be effective for that terminal only

@MestreLion — you are right. I was mentioning it for convenience for the current terminal. Forgot to add that.

What if I already have something in PATH? Could I append to it like PATHS work in Windows? For example I have PATH=»$HOME/bin:$HOME/.local/bin:$PATH» already.

To reload .profile and take changes effects without logout/login, run:

You can add the path to /etc/environment , but be aware that no shell expansions will work; the variable will be set to literally the characters you enter.

Out of the two methods(adding export command in .profile and adding full path name to PATH in etc/environment), which should be preferred?

Before setting a PATH variable, you need to understand why you are setting the PATH variable. The Path variable is where the system tries to search when you issue some command in your terminal.

Example: whereis ls command shows ls is there inside /bin . The ls command only works if /bin is registered in the path variable.

echo $PATH gives the currently registered locations. If you want to add another custom location to your path variable there are several ways you can try.

export PATH="$PATH:/someLocation"
export PATH="$PATH:/someLocation"

Add this line into the .bashrc file present in your home folder. Which is called every time a new bash shell is created. This means you get a new Path variable exported every time a new terminal is opened. But this variable is created for only bash shells. You can use the old Path variable in other shells(ksh, sh, ssh ..).

export PATH="$PATH:/someLocation"

Add this line into the .profile file present in your home folder. Which is called every time you log in. This means you get a new Path variable exported every time your session is created. Which is available everywhere.

If you can’t find the .profile or .bashrc file in your home folder, try to create a new one. Sometimes these files won’t be created by the system.

ps: Works in ubuntu. Open to any corrections.

Источник

Переменная PATH в Linux

Когда вы запускаете программу из терминала или скрипта, то обычно пишете только имя файла программы. Однако, ОС Linux спроектирована так, что исполняемые и связанные с ними файлы программ распределяются по различным специализированным каталогам. Например, библиотеки устанавливаются в /lib или /usr/lib, конфигурационные файлы в /etc, а исполняемые файлы в /sbin/, /usr/bin или /bin.

Таких местоположений несколько. Откуда операционная система знает где искать требуемую программу или её компонент? Всё просто — для этого используется переменная PATH. Эта переменная позволяет существенно сократить длину набираемых команд в терминале или в скрипте, освобождая от необходимости каждый раз указывать полные пути к требуемым файлам. В этой статье мы разберёмся зачем нужна переменная PATH Linux, а также как добавить к её значению имена своих пользовательских каталогов.

Переменная PATH в Linux

Для того, чтобы посмотреть содержимое переменной PATH в Linux, выполните в терминале команду:

На экране появится перечень папок, разделённых двоеточием. Алгоритм поиска пути к требуемой программе при её запуске довольно прост. Сначала ОС ищет исполняемый файл с заданным именем в текущей папке. Если находит, запускает на выполнение, если нет, проверяет каталоги, перечисленные в переменной PATH, в установленном там порядке. Таким образом, добавив свои папки к содержимому этой переменной, вы добавляете новые места размещения исполняемых и связанных с ними файлов.

Читайте также:  My games cloud linux

Для того, чтобы добавить новый путь к переменной 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 can I edit the $PATH on linux?

To permanently store your path, you have a few options.

I suggest you read the Ubuntu community wiki on Environment Variables but the short answer is the best place is ~/.profile for your per-user PATH setting or /etc/profile for global settings.

Change PATH:

export PATH=$PATH:/your/new/path/here 
export PATH=:/your/new/path/here:/another/new/path/here 

It is important to note that there are many occasions your profile is not run (such as when a script is run by cron). If you need a specific path to be set in PATH, a script must set that path. That said, scripts should never rely on anything being in their paths and should always use absolute paths, anything else is a security issue.

Reader, if you want to edit the $PATH on Linux, not just add a path to it, see the answer to superuser.com/questions/1353497/removing-directories-from-path instead.

PATH=$PATH:newPath1:newPAth2 export PATH 

It depends on the shell you’re using. On Solaris (I know the question is about Linux) one of the shells (can’t remember which one off the top of my head) requires that you do the export separately from setting the value in a script. So I’ve just gotten into the habit of doing it on 2 lines.

You can also put this in the global environment:

sudo emacs /etc/environment 

Append to the entries already in your path

Читайте также:  Установка арч линукс wifi

It has already been answered on how to do that, but I’d like to give you a little tip. Here is whatI do:

I have a directory called .bash.d in my $HOME and within that I keep a set of shell scripts that do stuff to my environment (for instance setup maven correctly, modify the path, set my prompt etc.). I keep this under version control by using git, which makes it easy to go back to a working version of your env, if you screw something up badly. To get all the modifications, I simply source all files in that dir at the end of my .bashrc like this:

for i in $HOME/.bash.d/*; do source $i; done unset i 

This gives you a very flexible environment that you can easily modify and restore + you are able to export it to other machines just by using git.

Источник

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.

Источник

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