Path configuration file linux

Переменная 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, но только для текущего пользователя:

Читайте также:  Gcc компилятор linux установка

Выводы

В этой статье мы рассмотрели вопрос о том, зачем нужна переменная окружения PATH в 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.

Читайте также:  Как определить мой адрес linux

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:

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.

Читайте также:  Apt через прокси linux

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.

Источник

Find The Configuration File Path Of my.cnf, http.conf, apache2.conf, And php.ini Files

How To Find Configuration File Path In Linux

In this post, we will learn how to find the configuration file path of php.ini files in PHP and my.conf file in MySQL database and http.conf file in Apache, which makes LAMP (Linux, Apache, MySQL, / MariaDB, PHP).

A configuration file actually contains application settings or system settings. This file allows programmers and system administrators to control an application or system operation. As a system administrator, it is important to know the config files’ location, and find the configuration file path is a valuable skill.

In the Linux Directory structure, the /etc. Directory or sub-directories are where the application’s configuration files or system-related configuration files are stored.

Although this is actually the main path of config files, some programmers choose other directories to store config files.

find the configuration file path

How To Find my.conf Configuration File Path In MySQL

You can find the MySQL configuration file oath using the MySQL or mysqladmin command (MySQL server management client).

The following command will show you the MySQL or mysqladmin guide page, which includes a section that talks about files (config files/settings) through which the default options are read and called.

In the following command, the -A option in the grep command displays the line number of the desired contact after the matching line.

# mysql --help | grep -A1 'Default options'
# mysqladmin --help | grep -A1 'Default options'

Find mysql file path

How To Find php.ini Configuration File Path In PHP

PHP can be controlled through the terminal using the PHP command and used with the -i option to display PHP information and settings, and using the grep command, you can find the PHP settings file as below.

# php -i | grep "Loaded Configuration File"

Find php.ini file in PHP

How To Find http.conf / apache2.conf Configuration File Path In Apache

You can use apache2 directly (which is often not recommended) or manage it using the apache2ctl control interface, as in the example below, using the -V option (an option that displays the version and parameters of apache2).

--------- On CentOS / RHEL / Fedora --------- # apachectl -V | grep SERVER_CONFIG_FILE --------- On Debian / Ubuntu / Linux Mint --------- # apache2ctl -V | grep SERVER_CONFIG_FILE Find the path http.conf in php

find http.conf in Apache

Conclusion

In this article, we found how to find a configuration file path in a Linux VPS.

Remember to share your valuable comments about this post if you know about other possible ways to find the Linux configuration file path.

Источник

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