Add to your path environment variable 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.

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 спроектирована так, что исполняемые и связанные с ними файлы программ распределяются по различным специализированным каталогам. Например, библиотеки устанавливаются в /lib или /usr/lib, конфигурационные файлы в /etc, а исполняемые файлы в /sbin/, /usr/bin или /bin.

Читайте также:  Linux bash array in array

Таких местоположений несколько. Откуда операционная система знает где искать требуемую программу или её компонент? Всё просто — для этого используется переменная 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 и вручную дописать туда нужное значение:

sudo vi /etc/environment

Можно поступить и иначе. Содержимое файла .bashrc выполняется при каждом запуске оболочки Bash. Если добавить в конец файла команду export, то для каждой загружаемой оболочки будет автоматически выполняться добавление имени требуемой папки в переменную PATH, но только для текущего пользователя:

Выводы

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

Источник

Adding a Directory to the Path

[ Linux Library | Troubleshooters.Com | Email Steve Litt | Copyright Notice ]

Contents:

Executive Summary

Disclaimer

Pre and Post Pathing

Linux determines the executable search path with the $PATH environment variable. To add directory /data/myscripts to the beginning of the $PATH environment variable, use the following:

To add that directory to the end of the path, use the following command:
But the preceding are not sufficient because when you set an environment variable inside a script, that change is effective only within the script. There are only two ways around this limitation:

  1. If, within the script, you export the environment variable it is effective within any programs called by the script. Note that it is not effective within the program that called the script.
  2. If the program that calls the script does so by inclusion instead of calling, any environment changes in the script are effective within the calling program. Such inclusion can be done with the dot command or the source command. Examples:
    . $HOME/myscript.sh
    source $HOME/myscript.sh

Inclusion basically incorporates the «called» script in the «calling» script. It’s like a #include in C. So it’s effective inside the «calling» script or program. But of course, it’s not effective in any programs or scripts called by the calling program. To make it effective all the way down the call chain, you must follow the setting of the environment variable with an export command.

As an example, the bash shell program incorporates the contents of file .bash_profile by inclusion. So putting the following 2 lines in .bash_profile:
effectively puts those 2 lines of code in the bash program. So within bash the $PATH variable includes $HOME/myscript.sh, and because of the export statement, any programs called by bash have the altered $PATH variable. And because any programs you run from a bash prompt are called by bash, the new path is in force for anything you run from the bash prompt.

The bottom line is that to add a new directory to the path, you must append or prepend the directory to the $PATH environment variable within a script included in the shell, and you must export the $PATH environnment variable. The only remaining question is: In which script do you place those two lines of code?

Читайте также:  Windows api error access denied

Adding to a Single User’s Path

To add a directory to the path of a single user, place the lines in that user’s .bash_profile file. Typically, .bash_profile already contains changes to the $PATH variable and also contains an export statement, so you can simply add the desired directory to the end or beginning of the existing statement that changes the $PATH variable. However, if .bash_profile doesn’t contain the path changing code, simply add the following two lines to the end of the .bash_profile file:

Adding to All Users’ Paths (except root)

You globally set a path in /etc/profile. That setting is global for all users except user root. Typical /etc/profile files extensively modify the $PATH variable, and then export that variable. What that means is you can modify the path by appending or prepending the desired directory(s) in existing statements modifying the path. Or, you can add your own path modification statements anywhere before the existing export statement. In the very unlikely event that there are no path modification or export statements in /etc/profile, you can insert the following 2 lines of code at the bottom of /etc/profile:

Adding to the Path of User root

Summary

Place that code, or whatever part of that code isn’t already incorporated, in one of the following places:

Источник

Environment variables

An environment variable is a named object that contains data used by one or more applications. In simple terms, it is a variable with a name and a value. The value of an environmental variable can for example be the location of all executable files in the file system, the default editor that should be used, or the system locale settings. Users new to Linux may often find this way of managing settings a bit unmanageable. However, environment variables provide a simple way to share configuration settings between multiple applications and processes in Linux.

Contents

Utilities

The coreutils package contains the programs printenv and env. To list the current environmental variables with values:

The env utility can be used to run a command under a modified environment. The following example will launch xterm with the environment variable EDITOR set to vim . This will not affect the global environment variable EDITOR .

The Bash builtin set allows you to change the values of shell options and set the positional parameters, or to display the names and values of shell variables. For more information, see the set builtin documentation.

Each process stores their environment in the /proc/$PID/environ file. This file contains each key value pair delimited by a nul character ( \x0 ). A more human readable format can be obtained with sed, e.g. sed ‘s:\x0:\n:g’ /proc/$PID/environ .

Defining variables

Globally

Most Linux distributions tell you to change or add environment variable definitions in /etc/profile or other locations. Keep in mind that there are also package-specific configuration files containing variable settings such as /etc/locale.conf . Be sure to maintain and manage the environment variables and pay attention to the numerous files that can contain environment variables. In principle, any shell script can be used for initializing environmental variables, but following traditional UNIX conventions, these statements should only be present in some particular files.

The following files should be used for defining global environment variables on your system: /etc/environment , /etc/profile and shell specific configuration files. Each of these files has different limitations, so you should carefully select the appropriate one for your purposes.

  • /etc/environment is used by the pam_env module and is shell agnostic so scripting or glob expansion cannot be used. The file only accepts variable=value pairs. See pam_env(8) and pam_env.conf(5) for details.
  • /etc/profile initializes variables for login shells only. It does, however, run scripts and can be used by all Bourne shell compatible shells.
  • Shell specific configuration files — Global configuration files of your shell, initializes variables and runs scripts. For example Bash#Configuration files or Zsh#Startup/Shutdown files.

In this example, we add

/bin directory to the PATH for respective user. To do this, just put this in your preferred global environment variable config file ( /etc/profile or /etc/bash.bashrc ):

Per user

You do not always want to define an environment variable globally. For instance, you might want to add /home/my_user/bin to the PATH variable but do not want all other users on your system to have that in their PATH too. Local environment variables can be defined in many different files:

/.pam_environment is the user specific equivalent of /etc/security/pam_env.conf [1], used by pam_env module. See pam_env(8) and pam_env.conf(5) for details.

  • User configuration files of your shell, for example Bash#Configuration files or Zsh#Startup/Shutdown files.
  • systemd will load environment variables from

    To add a directory to the PATH for local usage, put following in

    To update the variable, re-login or source the file: $ source

    /.bashrc etc. This means that, for example, dbus activated programs like Gnome Files will not use them by default. See Systemd/User#Environment variables.
    Reading

    Читайте также:  Windows 10 брандмауэр блокирует сетевые папки

    /.pam_environment is deprecated and the feature will be removed at some point in the future.

    Graphical environment

    Environment variables for Xorg applications can be set in xinitrc, or in xprofile when using a display manager, for example:

    The factual accuracy of this article or section is disputed.

    /.config/environment.d/ on Wayland sessions is GDM-specific behavior. (Discuss in Talk:Environment variables)

    Applications running on Wayland may use systemd user environment variables instead, as Wayland does not initiate any Xorg related files:

    To set environment variables only for a specific application instead of the whole session, edit the application’s .desktop file. See Desktop entries#Modify environment variables for instructions.

    Per session

    Sometimes even stricter definitions are required. One might want to temporarily run executables from a specific directory created without having to type the absolute path to each one, or editing shell configuration files for the short time needed to run them.

    In this case, you can define the PATH variable in your current session, combined with the export command. As long as you do not log out, the PATH variable will be using the temporary settings. To add a session-specific directory to PATH , issue:

    Examples

    The following section lists a number of common environment variables used by a Linux system and describes their values.

    • DE indicates the Desktop Environment being used. xdg-open will use it to choose more user-friendly file-opener application that desktop environment provides. Some packages need to be installed to use this feature. For GNOME, that would be libgnomeAUR ; for Xfce this is exo . Recognised values of DE variable are: gnome , kde , xfce , lxde and mate .

    The DE environment variable needs to be exported before starting the window manager. For example: This will make xdg-open use the more user-friendly exo-open, because it assumes it is running inside Xfce. Use exo-preferred-applications for configuring.

    • DESKTOP_SESSION is similar to DE , but used in LXDE desktop environment: when DESKTOP_SESSION is set to LXDE , xdg-open will use PCManFM file associations.
    • PATH contains a colon-separated list of directories in which your system looks for executable files. When a regular command (e.g. ls, systemctl or pacman) is interpreted by the shell (e.g. bash or zsh), the shell looks for an executable file with the same name as your command in the listed directories, and executes it. To run executables that are not listed in PATH , a relative or absolute path to the executable must be given, e.g. ./a.out or /bin/ls .
    • HOME contains the path to the home directory of the current user. This variable can be used by applications to associate configuration files and such like with the user running it.
    • PWD contains the path to your working directory.
    • OLDPWD contains the path to your previous working directory, that is, the value of PWD before last cd was executed.
    • TERM contains the type of the running terminal, e.g. xterm-256color . It is used by programs running in the terminal that wish to use terminal-specific capabilities.
    • MAIL contains the location of incoming email. The traditional setting is /var/spool/mail/$LOGNAME .
    • ftp_proxy and http_proxy contains FTP and HTTP proxy server, respectively:
    • MANPATH contains a colon-separated list of directories in which man searches for the man pages.
    • INFODIR contains a colon-separated list of directories in which the info command searches for the info pages, e.g., /usr/share/info:/usr/local/share/info
    • TZ can be used to to set a time zone different to the system zone for a user. The zones listed in /usr/share/zoneinfo/ can be used as reference, for example TZ=»:/usr/share/zoneinfo/Pacific/Fiji» . When pointing the TZ variable to a zoneinfo file, it should start with a colon per the GNU manual.

    Default programs

    • SHELL contains the path to the user’s preferred shell. Note that this is not necessarily the shell that is currently running, although Bash sets this variable on startup.
    • PAGER contains command to run the program used to list the contents of files, e.g., /bin/less .
    • EDITOR contains the command to run the lightweight program used for editing files, e.g., /usr/bin/nano . For example, you can write an interactive switch between gedit under X or nano, in this example:
    • VISUAL contains command to run the full-fledged editor that is used for more demanding tasks, such as editing mail (e.g., vi , vim, emacs etc).
    • BROWSER contains the path to the web browser. Helpful to set in an interactive shell configuration file so that it may be dynamically altered depending on the availability of a graphic environment, such as X:

    Using pam_env

    The PAM module pam_env(8) loads the variables to be set in the environment from the following files: /etc/security/pam_env.conf , /etc/environment and

    • /etc/environment must consist of simple VARIABLE=value pairs on separate lines, for example:
    • /etc/security/pam_env.conf and

    /.pam_environment share the same following format: @ and @ are special variables that expand to what is defined in /etc/passwd . The following example illustrates how to expand the HOME environment variable into another variable:

    Источник

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