How to add directory to path linux

How to add directory to system path in Linux

In Linux, the PATH environment variable stores the names of paths that will be searched for the executable files of any commands typed in the command line. The value of the PATH environment variable is a string containing a series of pathnames, each delimited by a colon. For instance, the default PATH on a typical system might look like this:

When you type a command such as cat and press Enter , the shell searches each of these directories for an executable file named cat. The first one it finds is the one it runs.

To view the current value of your PATH environment variable, you can use the echo command. As with all variables in the shell, when referring to the value you need to put a dollar sign before the variable name:

In the above example, the current value of path return you to the command prompt.

Setting PATH for your current shell session

You can set the value of PATH as you would any other shell variable, with the form NAME=VALUE, like this:

The problem with this command is that it will completely overwrite the values you had before, which you probably don’t want. If you want to add a new value in addition to the old ones. You can accomplish this by referring to PATH in the new definition, like this:

Using the command above adds your new path to the current value of PATH. Since the pathnames are searched in order, you probably want to add your new path at the end of the variable as we’ve done here. Instead, if you typed:

Your new path would be searched before, not after, the default system paths.

Using export to pass the PATH environment variable to child processes

This type of PATH definition sets the environment variable for your current shell session, but any new programs you run might not see the new path you’ve added. That’s because your shell lets you control the environment by requiring you to manually declare what environment variables are passed on to other programs and processes. You can accomplished this with the export command. If you run:

Any processes you run until you log out use the current value of PATH.

If you prefer, you can combine these two commands into a single line, for convenience. Put a semicolon between them so that the shell knows they’re separate commands:

If any of your pathnames have spaces in them, enclose the variable definition in quotation marks, to be safe.

Setting the PATH variable for every new shell session

The methods we’ve used so far only sets the environment variable for your current shell session; when you logout or close the terminal window, your changes will be forgotten. If you want to set PATH to a certain value every time you log in or start a new shell session, add it to your bash startup script. Every time you start an interactive shell session, bash reads the following files in order (if they exist), and executes the commands inside of them:

The first file, /etc/profile, is the default startup script for every user on the system. One or more of the remaining three files are located in the home directory of every user. Any of those three can be used, but it’s important to know that they will be searched for in this order.

Читайте также:  С windows servicing trustedinstaller exe что это

You can edit these files and manually change any lines containing PATH= definitions. Be careful if you do so, because these are the directories used to locate important operating system files.

If you want to add a path for your current user only, you can leave the other PATH= lines untouched. Add a line like this to the end of the file:

If you add this to the end of the .bash_profile file in your home directory, it takes effect every time your user starts a new shell session. If you add this to /etc/profile, it takes effect for every user on the system. Note that you need administrator privileges if you want to edit /etc/profile, so you can use sudo (or be logged in as root) to do so.

Источник

Как добавить каталог в PATH в Linux

Когда вы вводите команду в командной строке, вы в основном говорите оболочке запустить исполняемый файл с заданным именем. В Linux эти исполняемые программы, такие как ls , find , file и другие, обычно find в нескольких разных каталогах вашей системы. Любой файл с исполняемыми разрешениями, хранящийся в этих каталогах, может быть запущен из любого места. Наиболее распространенные каталоги, содержащие исполняемые программы, — это /bin , /sbin , /usr/sbin , /usr/local/bin и /usr/local/sbin .

Но как оболочка узнает, в каких каталогах искать исполняемые программы? Оболочка выполняет поиск по всей файловой системе?

Ответ прост. Когда вы вводите команду, оболочка просматривает все каталоги, указанные в $PATH пользователя, в поисках исполняемого файла с таким именем.

В этой статье показано, как добавить каталоги в $PATH в системах Linux.

Что такое $PATH в Linux

Переменная среды $PATH представляет собой список каталогов, разделенных двоеточиями, который сообщает оболочке, в каких каталогах следует искать исполняемые файлы.

Чтобы проверить, какие каталоги находятся в вашем $PATH , вы можете использовать команду printenv или echo :

Результат будет выглядеть примерно так:

Если у вас есть два исполняемых файла с одинаковым именем, расположенных в двух разных каталогах, оболочка запустит файл, который находится в каталоге, который идет первым в $PATH .

Добавление каталога в ваш $PATH

Бывают ситуации, когда вы можете захотеть добавить другие каталоги в $PATH . Например, некоторые программы могут быть установлены в разных местах или вы можете захотеть иметь специальный каталог для ваших личных сценариев, но иметь возможность запускать их, не указывая абсолютный путь к исполняемым файлам. Для этого вам просто нужно добавить каталог в ваш $PATH .

Допустим, у вас есть каталог bin расположенный в вашем домашнем каталоге, в котором вы храните сценарии оболочки. Чтобы добавить каталог в ваш $PATH введите:

Команда export экспортирует измененную переменную в среду дочернего процесса оболочки.

Теперь вы можете запускать свои сценарии, вводя имя исполняемого сценария без необходимости указывать полный путь к файлу.

Однако это изменение носит временный характер и действует только в текущем сеансе оболочки.

Чтобы сделать изменение постоянным, вам необходимо определить $PATH в файлах конфигурации оболочки. В большинстве дистрибутивов Linux при запуске нового сеанса переменные среды считываются из следующих файлов:

Глобальные файлы конфигурации оболочки, такие как /etc/environment и /etc/profile . Используйте этот файл, если хотите, чтобы новый каталог был добавлен всем пользователям системы $PATH .

Файлы конфигурации для конкретной оболочки пользователя. Например, если вы используете Bash, вы можете установить $PATH в файле

/.bashrc . Если вы используете Zsh, имя файла

В этом примере мы установим переменную в файле

/.bashrc . Откройте файл в текстовом редакторе и добавьте в конец следующую строку:

Сохраните файл и загрузите новый $PATH в текущий сеанс оболочки с помощью source команды:

Чтобы убедиться, что каталог был успешно добавлен, распечатайте значение вашего $PATH , набрав:

Выводы

Добавить новые каталоги к вашему пользователю или глобальной $PATH довольно просто. Это позволяет выполнять команды и сценарии, хранящиеся в нестандартных местах, без необходимости вводить полный путь к исполняемому файлу.

Те же инструкции применимы для любого дистрибутива Linux, включая Ubuntu, CentOS, RHEL, Debian и Linux Mint.

Читайте также:  Linux посмотреть имя компа

Не стесняйтесь оставлять комментарии, если у вас есть вопросы.

Источник

Как добавить каталог в PATH в Linux

How to Add a Directory to PATH in Linux

В этой статье показано, как добавить каталоги в ваши $PATH системы Linux.

Когда вы вводите команду в командной строке, вы в основном говорите оболочке запустить исполняемый файл с заданным именем. В Linux эти исполняемые программы , такие как ls , find , file и другие, как правило , живут внутри несколько различных каталогов в вашей системе. Любой файл с разрешением на выполнение, хранящийся в этих каталогах, может быть запущен из любого места. Наиболее распространенные каталоги , которые содержат исполняемые программы /bin , /sbin , /usr/sbin , /usr/local/bin и /usr/local/sbin .

Но как оболочка узнает, в каких каталогах искать исполняемые программы или оболочка выполняет поиск по всей файловой системе?

Ответ прост. Когда вы вводите команду, оболочка ищет во всех каталогах, указанных в пользовательской $PATH переменной, исполняемый файл с таким именем.

Что есть $PATH в Linux

$PATH Переменная окружающей среды является двоеточиями список каталогов, сообщает оболочке , какие каталоги для поиска исполняемых файлов.

Чтобы проверить, какие каталоги у вас есть $PATH , вы можете использовать команду printenv или echo :

Вывод будет выглядеть примерно так:

Если у вас есть два исполняемых файла с одинаковым именем, расположенные в двух разных каталогах, оболочка запустит файл, который находится в каталоге, который стоит первым в $PATH .

Добавление каталога в ваш $PATH

Есть ситуации, когда вы можете захотеть добавить другие каталоги в $PATH переменную. Например, некоторые программы могут быть установлены в разных местах, или вы можете захотеть иметь выделенный каталог для ваших личных записей, но сможете запускать их без указания абсолютного пути к исполняемым файлам. Для этого вам просто нужно добавить каталог в свой $PATH .

Допустим, у вас есть каталог с именем, bin расположенный в вашем домашнем каталоге, в котором вы храните свои сценарии оболочки. Чтобы добавить каталог к ​​вашему $PATH типу в:

Команда export экспортирует измененную переменную в дочерние среды процессов оболочки.

Теперь вы можете запускать свои скрипты, просто набрав имя исполняемого скрипта без указания полного пути к исполняемому файлу.

Однако это изменение носит временный характер и действует только в текущем сеансе оболочки.

Чтобы сделать изменение постоянным, вам нужно определить $PATH переменную в файлах конфигурации оболочки. В большинстве дистрибутивов Linux при запуске нового сеанса переменные среды считываются из следующих файлов:

Конфигурационные файлы глобальной оболочки, такие как /etc/environment и /etc/profile . Используйте этот файл, если вы хотите, чтобы новый каталог был добавлен всем системным пользователям $PATH .

Конфигурационные файлы для отдельных пользовательских оболочек. Например, если вы используете Bash, вы можете установить $PATH переменную в

/.bashrc файле, а если вы используете Zsh — имя файла

В этом примере мы установим переменную в

/.bashrc файле. Откройте файл в текстовом редакторе и добавьте в конце следующую строку:

Чтобы подтвердить, что каталог был успешно добавлен, напечатайте его значение $PATH , набрав:

Вывод

Добавить новые каталоги в вашу пользовательскую или глобальную $PATH переменную довольно просто. Это позволяет выполнять команды и сценарии, хранящиеся в нестандартных местах, без необходимости вводить полный путь к исполняемому файлу.

Те же инструкции применимы для любого дистрибутива Linux, включая Ubuntu, CentOS, RHEL, Debian и Linux Mint.

Источник

How to Add Directory to $PATH Variable in Linux

The environment variables control the behavior of the shell. Environment variables are the variables that set the working environment of the shell. Some of the environment variables are USER, HOME, SHELL, PWD, SHELL, PS1, PS2, etc.

The HOME variable contains the path of home directory of the user. Similarly, the other variables contain other values needed for the operation of the shell. This tutorial discusses an important shell environment variable called PATH and how you can add values to this variable.

In this tutorial, I will show you how to add a directory to your PATH variable in Linux. The $PATH variable display a list of all directories where Linux commands or executable files reside.

Show Variable Value

The shell interprets the value of a variable by the «$» sign. To display the value of a variable, precede the variable with «$» sign. The «echo» command is used to display the value of the variable. Let us display the value of the variable HOME:

Читайте также:  Windows current user information

What is PATH variable

The commands in Unix/Linux are the binary executable files. When you enter a command at the shell prompt, the binary file with that name is executed. So when a command is entered at the prompt, the shell searches for that binary file in some directories. These directories are listed in the PATH variable. Without the PATH variable, no command can be executed.

Now let’s show the current value of PATH variable.

The directories in this variable are separated by : (colon). At present, the shell searches the following directories for the binary executable files:

The order of the search path is also important. Suppose, you enter the ls command at the command line. Now at first, the shell searches /usr/local/sbin directory. If it does not find an executable file with that name in this directory, then it looks in the /usr/local/bin directory and then /usr/sbin, followed by /usr/bin and so on. If none of the directories specified in the PATH variable contains that file, then «command not found» error is displayed on the terminal.

Which command is used to find out the directory that contains a particular command. This command also uses the PATH variable to search for the command location. For example,

It means that when you type ls at the prompt and execute the ls command, then “/bin/ls” file is executed. In other words, location of ls command is “/bin/ls”. You can also find path of other commands with «which» command.

Add Directories to PATH

Now assume that you create your shell scripts in bin directory located in your home directory, i.e. in “

represents home directory); and now you want to add this directory to your PATH variable as well, so that you do not have to specify the path to your script every time you run the script.

The value of a variable is changed with the syntax “variable=value”. But here, we want to add a directory to the PATH variable. We can’t just write “PATH=

/bin” because it will overwrite all the previous values. We want to preserve the existing values contained in the variable. So, we use value of the variable, i.e. $PATH, for assigning new value. If it sounds confusing, don’t worry, it will be clear with the following command:

The «/root/bin» directory (/root is root user’s home directory) has been added to the path variable. Now you can execute your script as a command, without specifying the full path to the script. The export command ensures that the variables are passed to the child processes without affecting the existing environment variables.

Let’s take another example where you like to add a directory (/home/tom/scripts) for a user named ‘tom’ that may contain his scripts or binaries. You can place custom script path at the front of the PATH if the system wants to find it first.

To remove a path from the $PATH variable from the current session there is no straightforward command. Just get the current values of $PATH variable using «echo $PATH» and export again after removing unwanted paths. Or simply start a new shell.

How to Set PATH permanent

To set up $PATH variable permanent, have to add the above-mentioned command to the respective configuration file that launches shell. The most common file is

/.bashrc if you are using Bash. For zsh, add it to

You can appropriately use /etc/environment and /etc/profile which defines global environment variables.

/.bashrc file in your favorite text editor and run the following command:

And, to load variable to the current shell run source command, type:

Conclusion

In this tutorial, we have learned how to add a directory to the PATH environment variable in Linux. Hope you enjoyed reading this and please leave your suggestion in the below comment section.

Источник

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