Linux get system path

How can I find the system PATH in linux for any executable? (ubuntu distro) [duplicate]

I have tried using the command: echo $PATH, but I get a path that I do not recognize as an actual directory on my machine: «/home/user_name/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games» If I want to install a new program into the correct directory, how can I find the system PATH using the Terminal?

2 Answers 2

Well, these are the paths. Executables (Binary or Scripts with executable bit and valid bang-path) need to be placed there to be able to be executed without prepending a specific location.

Your problem is that you do not understand UNIX paths at all.

/home/user_name/bin /usr/local/sbin /usr/local/bin 

The colon : is used to separate paths when concatenating them within a string! So, in contrast to «windows» C:foo would mean: two paths (C and foo in the Unix/Linux world)

And I am pretty sure that all these different paths exist on your system.

And for that other implied question: determining the correct directory for a new executable might very much depend on your that new thing.

When you wrote a little script for yourself, you would typically put it into ~/bin. But things that should be used by other users might go to /usr/local/bin for example. For more details on that part; turn to the «duplicated» question suggested to you

Источник

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

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

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

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

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

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

Читайте также:  Sp flashtool на 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.

Источник

Show PATH of Environment Variables

An environment variable is a key:value pair in the form of key=value. The value itself can be a number, a location, text, or any other random string. The environment variables shape the system and define various attributes. For example, the HOME variable is used to set the current user’s home folder, while the SHELL variable contains information about the current user’s shell path. Although there are a large number of pre-defined environment variables, one can always create new ones or modify existing ones. This means that any environment variable can be shown/seen, edited, saved, and deleted. And though environment variables exist on every system, we will be focusing on the Linux system. In particular, in this tutorial, we will be learning about showing the PATH of the environment variables.

Environment Variables

In order to print out all of the environment variables, we type:

Читайте также:  Linux remove file bash

Untitled5

The latter will print out all the environment variables and their respective values.

Untitled

The printenv command is used to print out each and every environment variable. That is the key:value pairs. Some of the environment variables on my system are:

SHELL=/bin/bash
PWD=/home/kalyani
HOME=/home/kalyani
TERM=xterm-256color
USER=kalyani
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

The first thing to notice is a key:value pair. Of all these environment variables, one that we give specific attention to is the PATH environment variable.

PATH

PATH is an environment variable that allows the system to specifically find various executables by pointing them to the right directory. On Ubuntu, PATH would look something like this (this is on my system):

PATH = / usr / local / sbin: / usr / local / bin: / usr / sbin: / usr / bin: / sbin: / bin: / usr / games: /
usr / local / games: / snap / bin

PATH here is the key, and to the right of the PATH variable is its value. By convention, each path is separated by a colon (:). And separated by a colon are a large number of directories.

So when you enter a command, let’s take the command “cat” as an example; the shell will search each one of these directories one after another from left to right. If it is found in one of them, then it executes it. However, please note that it will search in the exact order that it is listed in. This means it won’t search /snap/bin first; it will search it last. Further, when it has searched the /usr/local/sbin directory, it won’t randomly pick another one to search but rather search the /usr/local/bin directory.

We notice that the cat command is found in /usr/bin, and as such when the system gets to /usr/bin, it will find the cat command, execute it, and terminate the search. This further means that if there were two versions of the “cat” command, the one that appears in the earlier directory would be executed, and the second one would be ignored. If the command is not found in any of the directories listed in the PATH environment variable, then a “command not found” error will be issued.

On a Linux system, there are a number of ways of displaying the PATH information.

PRINTENV

We can obviously display the path information using the printenv command. In order to print out the PATH information using the printenv command, you need to type printenv and then the name of the environment variable that you would like to display. In our case, it’d be PATH.

Untitled2

You can add any of the environment variables of your choice after the printenv command, and it will print it out for you.

Читайте также:  Днс через терминал линукс

Please note here that the word PATH has to be in all-capitals. Suppose that I write the following:

The latter returns absolutely nothing. This means no value is associated with the variable path (in lower case letters).

Untitled4

ECHO

Alternatively, the other common way of printing out the PATH environment variable is by using the echo command. The echo command is used to print out or echo out the value. Because PATH is a variable, in order to print it, we must add a dollar sign in front of it. Please also remember to keep all letters in the capital.

Untitled3

You can show the path individually using:

Untitled4

SED is used in this case to re-format the output by taking each path and placing them on a single line. In other words, substitute the colon with a new line.

Further, if we were to write the word PATH in lower case letters, we’d get the following:

Untitled

What this means is that everything here is case-sensitive.

Modifying PATH

The PATH variable can easily be modified as well. We can add to it – prepend or append. What’s more? We can make temporary changes or permanent changes.

There are 3 ways to modify PATH:

Temporarily:

export PATH = $PATH : / path / to / dir

export PATH = / path / to / dir: $PATH

To temporarily change the PATH, you can simply type the previous code into a terminal. However, this will be restricted to a single session.

Permanently (for the current user):

Edit the .bashrc file by adding export PATH=$PATH:/path/to/dir to it, and updating the the .bashrc file.

System-wide (for all users):

Modify the /etc/environment file. This is not recommended.

Once you have modified the PATH variable, you can again check the new PATH variable using the printenv command or the echo command.

So let’s try the temporary PATH change. Suppose that I type the following into my terminal:

export PATH = $PATH : / home / kalyani

Untitled

Please notice how the PATH is added to the end of the search directories.

Environment variables are a set of key:value pairs. They exist on every system, and on the Linux system, they can be viewed, edited, saved, and deleted. PATH, in particular, is an environment variable used to display the path to search for executables. When a command is issued, the system looks at the PATH environment variable to find its location. If found, the command works; otherwise, a “command not found” error is issued. Further, the PATH environment variable can be viewed using two distinct commands – the printenv command or the echo command. The PATH variable can also be modified prior to viewing in three distinct ways – temporarily, permanently, or system-wide.

Источник

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