Добавить папку path linux

Add a Directory to the PATH on Linux

Estamos traduciendo nuestros guías y tutoriales al Español. Es posible que usted esté viendo una traducción generada automáticamente. Estamos trabajando con traductores profesionales para verificar las traducciones de nuestro sitio web. Este proyecto es un trabajo en curso.

Have you ever wondered how certain executables on Linux can be accessed as simple commands from the command line? Have you wanted to be able to run a program on Linux without having to provide the entire path?

These are the problems the PATH variable is designed to solve. In this tutorial, learn more about what the PATH variable is and how it works. Then, see how you can add your own directories to the PATH , allowing you to run programs as simple commands.

Before You Begin

  1. Familiarize yourself with our Getting Started with Linode guide and complete the steps for setting your Linode’s hostname and timezone.
  2. This guide uses sudo wherever possible. Complete the sections of our How to Secure Your Server guide to create a standard user account, harden SSH access, and remove unnecessary network services.
  3. Update your system.
  4. On Debian and Ubuntu, use the following command:
 sudo apt update && sudo apt upgrade 

The steps in this guide are written for non-root users. Commands that require elevated privileges are prefixed with sudo . If you’re not familiar with the sudo command, see the Linux Users and Groups guide.

What Is the PATH Variable?

The $PATH environmental variable contains a colon-separated list of directories. These directories are where Linux looks for executables, allowing you to run these using only the executable names.

For instance, say you have an executable called program-to-run in the /usr/local/bin directory. Without that directory in your PATH , you would have to run the executable with:

Or by changing into the directory first and then running the executable:

cd /usr/local/bin ./program-to-run 

However, if you have the directory in your PATH , you can run the executable by simply giving its name as a command:

The PATH variable becomes especially useful when running specialized developer or system administrator tools as well as in-development applications. It allows you to run tools and applications efficiently while keeping them stored wherever best fits your needs.

View the PATH Variable

It can be useful to know what directories are already assigned to the PATH on your Linux system. You can do this easily with the echo command, like this:

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

As you can see from the output above, Linux systems come by default with several convenient directories already on the PATH .

But sometimes these directories alone do not meet your needs. That is when you should look to customizing the PATH variable’s contents.

How to Add a Directory to the PATH

Linux comes with several directories in the PATH by default, like you can see in the output above. Typically, these are enough. Most programs you install on Linux put their executables in one of the default directories, making them easy to start using immediately.

But sometimes this is not the case. The PATH variable does not cover executables that you download or create and store in non-default directories. But that kind of storage is often the case when using one-off programs, working with particular system administrator tools, or when developing executables.

In such cases and similar ones, you likely want the ability to add additional directories to the PATH variable to make executables easier to work with.

Fortunately, you can do just that using the export command. Here is an example, adding the /etc/custom-directory directory to the PATH :

export PATH="$PATH:/etc/custom-directory" 

After the above command, you can run executables stored in the custom-directory simply by providing the executables’ names as commands.

How exactly does the export command achieve this? Follow along with this breakdown of the command to understand how each part works:

  • export PATH= starts to define the PATH variable.
  • $PATH ensures that the new definition of PATH begins with all of the contents of the existing PATH . In other words, including the PATH variable here is how you expand on the variable’s contents rather than overwrite them.
  • :/etc/custom-directory adds the new directory. Notice the placement of the colon, which is necessary because the PATH list is colon-separated.

You can verify the updated contents of PATH using the echo command as shown above:

/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/etc/custom-directory

PATH Variable Scope

Executing the export command above only updates the PATH variable for the current session. Logging out and logging back into your Linux system results in the PATH being reset.

There are two methods available should you want to have your directory added to the PATH in a more permanent way.

    You can alter the PATH variable for a given user by adding the export command to that user’s shell configuration file. The location of the configuration file varies depending on the shell program. For Bash, the configuration file is typically ~/.bashrc :

Источник

Как добавить каталог в 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 :

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

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

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

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

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

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

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

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

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

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

  • Глобальные файлы конфигурации оболочки, такие как /etc/environment и /etc/profile . Используйте этот файл, если хотите, чтобы новый каталог был добавлен всем пользователям системы $PATH .
  • Файлы конфигурации для конкретной оболочки пользователя. Например, если вы используете Bash, вы можете установить $PATH в файле ~/.bashrc . Если вы используете Zsh, имя файла ~/.zshrc .

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

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

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

Выводы

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

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

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

Источник

How to Add a Directory to PATH in Linux

When you type a command on the command line, you’re basically telling the shell to run an executable file with the given name. In Linux, these executable programs like ls , find , file and others, usually live inside several different directories on your system. Any file with executable permissions stored in these directories can be run from any location. The most common directories that hold executable programs are /bin , /sbin , /usr/sbin , /usr/local/bin and /usr/local/sbin .

But how does the shell knows, what directories to search for executable programs? Does the shell search through the whole filesystem?

The answer is simple. When you type a command, the shell searches through all directories specified in the user $PATH variable for an executable file of that name.

This article shows how to add directories to your $PATH in Linux systems.

What is $PATH in Linux #

The $PATH environmental variable is a colon-delimited list of directories that tells the shell which directories to search for executable files.

To check what directories are in your $PATH , you can use either the printenv or echo command:

The output will look something like this:

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

If you have two executable files sharing the same name located in two different directories, the shell will run the file that is in the directory that comes first in the $PATH .

Adding a Directory to your $PATH #

There are situations where you may want to add other directories to the $PATH variable. For example, some programs may be installed in different locations, or you may want to have a dedicated directory for your personal scripts, but be able to run them without specifying the absolute path to the executable files. To do this, you simply need to add the directory to your $PATH .

Let’s say you have a directory called bin located in your Home directory in which you keep your shell scripts. To add the directory to your $PATH type in:

The export command will export the modified variable to the shell child process environments.

You can now run your scripts by typing the executable script name without needing to specify the full path to the file.

However, this change is only temporary and valid only in the current shell session.

To make the change permanent, you need to define the $PATH variable in the shell configuration files. In most Linux distributions when you start a new session, environment variables are read from the following files:

  • Global shell specific configuration files such as /etc/environment and /etc/profile . Use this file if you want the new directory to be added to all system users $PATH .
  • Per-user shell specific configuration files. For example, if you are using Bash, you can set the $PATH variable in the ~/.bashrc file. If you are using Zsh the file name is ~/.zshrc .

In this example, we’ll set the variable in the ~/.bashrc file. Open the file with your text editor and add the following line at the end of it:

Save the file and load the new $PATH into the current shell session using the source command:

To confirm that the directory was successfully added, print the value of your $PATH by typing:

Conclusion #

Adding new directories to your user or global $PATH variable is pretty simple. This allows you to execute commands and scripts stored on nonstandard locations without needing to type the full path to the executable.

The same instructions apply for any Linux distribution, including Ubuntu, CentOS, RHEL, Debian, and Linux Mint.

Feel free to leave a comment if you have any questions.

Источник

Читайте также:  Linux zip только файлы
Оцените статью
Adblock
detector