Linux export path and save

Переменная 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 и как добавлять к её значению новые пути поиска исполняемых и связанных с ними файлов. Как видите, всё делается достаточно просто. Таким образом вы можете добавить столько папок для поиска и хранения исполняемых файлов, сколько вам требуется.

Читайте также:  Workcentre 3345 drivers linux

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

How to Export a Path in .Bashrc

When a command is launched on Linux, the operating system looks in the environment variable which is known as PATH for executable files. When we employ these paths, we can run the commands without having to provide a specific path.

What Are Environmental Variables in Linux?

In Linux, the environment variables are a collection of configurable named variables that were already saved on the device that is run on the terminal of Linux-based devices. The environment variable contains a name, and it has a specified value in it. We can alter the default path in Linux using the environment variable. For instance, the environment variable may keep track of the default search engine, the location of executable commands, or the keyboard configuration.

Here are the different techniques to view the default path. You can also add the path by yourself:

Technique 1: Default “Path” in Linux

If you want to display the default path in Linux, we write the following command in the Linux terminal:

The following is the default path of the Linux device. The file paths may vary somewhat based on your Linux system. As you verify in the following output, the colon “:” is used to separate each “Path” directory in the terminal, as well as some directories which are listed by default in the output. When a command is started, the system scans these directories from left to right.

If we write the “echo $Path” command and we didn’t get the path of the directory, we have to add the directory path. Here is an example: when we enter the command to view the path, we didn’t view any path as you can see in the following illustration:

Technique 2: Adding the Inode to a Temporary Path Variable

To create a temporary Path in Linux, we write the following command in the terminal:

linux@linux-VirtualBox:~$ export PATH = / usr / local / sbin: / usr / local / bin: / usr / sbin: / sbin: / bin:

/ usr / games: / usr / local / games: / snap / bin

Now, we can access the path by writing “echo” along with the path_name.

Here is the desired output of the command:

This method of creation only exists until we end the existing terminal which means that it is a temporary session. The PATH variable reverts to its default settings whenever you quit the existing activity and start another one, and the recently inserted inode won’t be present. An inode must be used to hold the PATH so that it is persistent throughout several terminal sessions. We use another method where it holds the inode permanently in the terminal session.

Technique 3: Permanently Adding the Inode at the End to a Path Variable

This method adds the Path permanently in the terminal configuration file. To add permanently, we use the “bashrc” command. Here is the complete statement:

After hitting enter, we get the following output:

To exit from the bashrc terminal, there are hints to exit the bashrc terminal at the bottom of the terminal. After coming back to the main terminal, write the “export PATH”. Then, assign the path of the inode of your choice in the Linux terminal. The following is the complete command to give the path of the inode:

Читайте также:  Установка системного загрузчика grub kali linux

After writing the previous command, wait so that the changes are made after entering the path of your choice in the Linux terminal. Then, save the bashrc file and close it.

Once a new terminal session is launched, the PATH variable is modified. Now, just employ the “source” statement to implement the modifications to the existing session. Use the following command to implement the source command to the bashrc file:

In the future, if you want to add a new inode in the bashrc file, use the colon “:” to add the directories to the existing “export” statement.

After importing the updated bashrc file, check whether the Linux existing address is saved in the Linux device default path or not. The following is the command to confirm the updated address/path. First, write “echo” and then write the “$PATH” to access the updated address.

Here is the desired output of the previously-implemented commands in the Linux terminal. As you see in the following output, we have now an updated address in the bashrc file because the new inode address is added to the previous path which is “/home/linux”.

Here is another command in Linux to display the current existing address in the bashrc file in the Linux terminal:

The following is the output of the “printenv” command which displays the same output because it works the same as “echo” in the Linux terminal:

Technique 4: Adding the Inode at the Start to a Path Variable in Linux Permanently

If you want to add a particular path at the start of the existing path in the bashrc file in Linux, you have to follow the instruction that is written in the following. This method is the same as we previously did. The only difference is to add the path before accessing the “$PATh” in the bashrc file in Linux.

After writing the previous command in the bashrc file, we now implement these changes in the file.Use the “source” command to update the bashrc file in Linux like this:

After updating the file, we now want to check whether the modifications are done or not in the bashrc file in the Linux terminal. Write the following written command:

The following is the output of the modification which we did in the bashrc file in the Linux terminal:

As you see in the output, the new path is added at the start of the previous path that is permanently saved in the bashrc file.

Conclusion

In this tutorial, we learned about one of the environment variables in Linux called “Path.” We learned how to get the default path in the terminal and what to do to add the path if it is not already there. With a thorough explanation, we learned how to permanently add the path at the beginning and at the end of the existing address in the bashrc file.

Читайте также:  Чем линукс лучше программистам

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.

Источник

Permanent PATH variable

How will I make this /media/De Soft/mongodb/bin PATH variable permanent? Everyone is saying » export PATH=$PATH:media/De\ Soft/mongodb/bin to your ~/.profile , or .bashrc , or .zshenv depending on your shell». I don’t know what is ~/.profile , or .bashrc , or .zshenv . What do they do actually? How will I add export PATH=$PATH:my/path to my .profile/.bashrc/.zshenv? I’m using 64 bit Ubuntu 14.04 LTS with default terminal.

4 Answers 4

They are configuration files. One way:

  • Open a terminal window using Ctrl+Alt+T
  • Run the command gedit ~/.profile
  • Add the line export PATH=$PATH:/media/De\ Soft/mongodb/bin to the bottom and save
  • Log out and log in again

A safer way is to use quotes. Doing so is necessary if one or more directories in the original PATH contain spaces. So:

export PATH="$PATH:/media/De Soft/mongodb/bin" 

@GunnarHjalmarsson, do I really need to export PATH var? Maybe, it is done by default in some other script? I have checked by ~/.profile and a PATH var is there, but it is not explicitly exported: PATH=~/.local/bin:$JAVA_HOME/bin:$PATH

@yuranos87: No, you are right; when modifying PATH in ~/.profile , exporting is redundant, since PATH already is an environment variable.

@timbo: That does not make the variable available to already started processes in the session (except for the current terminal).

Don’t you need a quote mark in the string as in export PATH=»$PATH:/media/De\ Soft/mongodb/bin» ? Is it optional?

To permanently change PATH you need to make changes to /etc/environment file. Make a backup before editing:

sudo cp /etc/environment /etc/environment.bak sudo nano /etc/environment 
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games" 

Paths are delimited by : so to add a new path say x/y/z this will how our /etc/environment looks like:

PATH="x/y/z:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games" 

Hi, i did what you wrote here and $ echo $PATH reveals: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin but: sudo nano /etc/environment reveals alot more. like games, i edited the path file, it shows up in NANO, but not in terminal using $echo $PATH, am i alrite?

@NaturalDemon: It doesn’t matter how you did that as long as PATH variable contains it correctly you are OK.

Type the following in a terminal window

export PATH=/media/De\ Soft/mongodb/bin:$PATH 

Close the terminal and restart the computer. The path should include /media/De\ Soft/mongodb/bin when you type this in the terminal:

That only works for current terminal session. It needs to be in ~/.profile (or ~/.bashrc on common GNU/Linux distros. even ~/.bash_profile ) to be run on every console load.

@NiveditaVelagaleti: No it’s not unless you make it persistent via a config file. The terminal command does not modify PATH persistently.

To be clear, I should not put this in ~/.bashrc or ~/.bash_profile if I want he variable ( PATH ) to be available to most applications, correct? The documentation says, «Shell config files such as ~/.bashrc , ~/.bash_profile , and ~/.bash_login . may work on Bash shells for programs started from the shell, [but] variables set in those files are not available by default to programs started from the graphical environment in a desktop session.»

Источник

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