Как изменить переменную path linux

On Linux, how can I add a directory to the $PATH so it remains persistent across different sessions? Background I'm trying to add a directory to my path so it will always be in my Linux path. I've ...

On Linux, how can I add a directory to the $PATH so it remains persistent across different sessions?

Background

I’m trying to add a directory to my path so it will always be in my Linux path. I’ve tried:

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

This works, however each time I exit the terminal and start a new terminal instance, this path is lost, and I need to run the export command again.

How can I do it so this will be set permanently?

Amin's user avatar

Amin

1,3351 gold badge17 silver badges29 bronze badges

asked Feb 1, 2013 at 0:57

Ali's user avatar

1

You need to add it to your ~/.profile or ~/.bashrc file. 

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

Depending on what you’re doing, you also may want to symlink to binaries:

cd /usr/bin
sudo ln -s /path/to/binary binary-name

Note that this will not automatically update your path for the remainder of the session. To do this, you should run:

source ~/.profile 
or
source ~/.bashrc

Greenbeard's user avatar

answered Feb 1, 2013 at 1:01

mpowered's user avatar

mpoweredmpowered

12.9k2 gold badges15 silver badges18 bronze badges

26

There are multiple ways to do it. The actual solution depends on the purpose.

The variable values are usually stored in either a list of assignments or a shell script that is run at the start of the system or user session. In case of the shell script you must use a specific shell syntax and export or set commands.

System wide

  1. /etc/environment List of unique assignments. Allows references. Perfect for adding system-wide directories like /usr/local/something/bin to PATH variable or defining JAVA_HOME. Used by PAM and systemd.

  2. /etc/environment.d/*.conf List of unique assignments. Allows references. Perfect for adding system-wide directories like /usr/local/something/bin to PATH variable or defining JAVA_HOME. The configuration can be split into multiple files, usually one per each tool (Java, Go, and Node.js). Used by systemd that by design do not pass those values to user login shells.

  3. /etc/xprofile Shell script executed while starting X Window System session. This is run for every user that logs into X Window System. It is a good choice for PATH entries that are valid for every user like /usr/local/something/bin. The file is included by other script so use POSIX shell syntax not the syntax of your user shell.

  4. /etc/profile and /etc/profile.d/* Shell script. This is a good choice for shell-only systems. Those files are read only by shells in login mode.

  5. /etc/<shell>.<shell>rc. Shell script. This is a poor choice because it is single shell specific. Used in non-login mode.

User session

  1. ~/.pam_environment. List of unique assignments, no references allowed. Loaded by PAM at the start of every user session irrelevant if it is an X Window System session or shell. You cannot reference other variables including HOME or PATH so it has limited use. Used by PAM.

  2. ~/.xprofile Shell script. This is executed when the user logs into X Window System system. The variables defined here are visible to every X application. Perfect choice for extending PATH with values such as ~/bin or ~/go/bin or defining user specific GOPATH or NPM_HOME. The file is included by other script so use POSIX shell syntax not the syntax of your user shell. Your graphical text editor or IDE started by shortcut will see those values.

  3. ~/.profile, ~/.<shell>_profile, ~/.<shell>_login Shell script. It will be visible only for programs started from terminal or terminal emulator. It is a good choice for shell-only systems. Used by shells in login mode.

  4. ~/.<shell>rc. Shell script. This is a poor choice because it is single shell specific. Used by shells in non-login mode.

Notes

GNOME on Wayland starts a user login shell to get the environment. It effectively uses the login shell configurations ~/.profile, ~/.<shell>_profile, ~/.<shell>_login files.

Man pages

  • environment
  • environment.d https://linux.die.net/man/1/environment.d
  • bash
  • dash

Distribution-specific documentation

  • Ubuntu
  • Arch Linux

Difference between Login Shell and Non-Login Shell?

Peter Mortensen's user avatar

answered Nov 16, 2014 at 21:29

Grzegorz Żur's user avatar

Grzegorz ŻurGrzegorz Żur

46.3k14 gold badges111 silver badges103 bronze badges

11

In Ubuntu, edit /etc/environment. Its sole purpose is to store environment variables. Originally the $PATH variable is defined here.

This is a paste from my /etc/environment file:

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

So you can just open up this file as root and add whatever you want.

For immediate results,

Run (try as normal user and root):

source /etc/environment && export PATH

If you use Z shell (zsh), add this line right after the comments in /etc/zsh/zshenv file:

source /etc/environment

I encountered this little quirk on Ubuntu 15.10 (Wily Werewolf), but if your zsh is not getting the correct PATH, this could be why.

answered May 27, 2014 at 16:27

trve.fahad's user avatar

trve.fahadtrve.fahad

4,3492 gold badges16 silver badges25 bronze badges

13

For Bash, you can put the export declaration in ~/.bashrc. For example, my .bashrc contains this line:

export PATH=/var/lib/gems/1.8/bin:/home/ash/.bin:$PATH

answered Feb 1, 2013 at 0:59

ashastral's user avatar

ashastralashastral

2,7981 gold badge20 silver badges32 bronze badges

10

You may set $PATH permanently in two ways.

  1. To set the path for a particular user:

    You may need to make the entry in file .bash_profile in the home directory for the user.

    E.g, in my case I will set the java path in the Tomcat user profile*

     echo "export PATH=$PATH:/path/to/dir" >> /home/tomcat/.bash_profile
    
  2. To set a common path for all system users, you may need to set the path like this:

     echo "export PATH=$PATH:/path/to/dir" >> /etc/profile
    

Peter Mortensen's user avatar

answered Jan 3, 2014 at 11:35

Mohit M's user avatar

Mohit MMohit M

7497 silver badges15 bronze badges

3

You can use on CentOS or Red Hat Linux (RHEL) for the local user:

echo $"export PATH=$PATH:$(pwd)" >> ~/.bash_profile

This adds the current directory (or you can use another directory) to the PATH. This makes it permanent, but it takes effect at the next user logon.

If you don’t want do a re-logon, then you can use:

source ~/.bash_profile

That reloads the # User specific environment and startup programs. This comment is present in file .bash_profile.

Peter Mortensen's user avatar

answered Oct 21, 2016 at 4:11

Daniel Antonio Nuñez Carhuayo's user avatar

You can also set it permanently, editing one of these files:

/etc/profile (for all users)

~/.bash_profile (for current user)

~/.bash_login (for current user)

~/.profile (for current user)

You can also use /etc/environment to set a permanent PATH environment variable, but it does not support variable expansion.

Extracted from: Linux: Añadir ruta al PATH

Peter Mortensen's user avatar

answered Jun 29, 2016 at 8:59

Delucaramos's user avatar

1

I think the most elegant way is:

  1. Add this in the ~/.bashrc file.

    Run this command:

     gedit ~/.bashrc
    

    Add your path inside it:

     export PATH=$PATH:/opt/node/bin
    
  2. source ~/.bashrc

(Ubuntu)

Peter Mortensen's user avatar

answered Nov 4, 2017 at 13:40

Himanshu sharma's user avatar

Himanshu sharmaHimanshu sharma

7,2494 gold badges42 silver badges74 bronze badges

1

  1. Modify the «/etc/profile» file:

    vi /etc/profile
    

    Press the I key to enter editing mode and move the cursor to the end of the file. Additional entries:

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

    Press the Esc key to exit edit mode, and :wq to save the file.

  2. Make the configuration effective

    source /etc/profile
    

    Explanation:

    The profile file works for all users. If you want it to be valid only for the active user, change the «.bashrc» file.

Peter Mortensen's user avatar

answered Nov 23, 2018 at 9:24

Jia's user avatar

JiaJia

3343 silver badges4 bronze badges

I stumbled across this question yesterday when searching for a way to add a folder containing my own scripts to the PATH — and was surprised to find out that my own ~/.profile file (on Linux Mint 18.1) already contained this:

# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
    PATH="$HOME/bin:$PATH"
fi

Thus, all I had to do was create the folder ~/bin and put my scripts there.

Peter Mortensen's user avatar

answered Mar 4, 2017 at 11:09

RobertG's user avatar

RobertGRobertG

1,4151 gold badge20 silver badges41 bronze badges

2

You can add that line to your console configuration files (e.g., .bashrc, or to .profile).

Peter Mortensen's user avatar

answered Feb 1, 2013 at 0:59

aqua's user avatar

aquaaqua

3,15928 silver badges40 bronze badges

3

After so much research, I found a simple solution for this (I am using Elementary OS), inspired by Flutter – Step by Step Installation on Linux – Ubuntu.

Run the following command to open the .bashrc file in edit mode. (You
may also use vi or any other editor).

~$ sudo nano ~/.bashrc

Add the following line at the end of the file and save.

export PATH="[FLUTTER_SDK_PATH]/flutter/bin:$PATH"

For example:

export PATH="/home/rageshl/dev/flutter/bin:$PATH"

enter image description here

I believe this is the permanent solution for setting the path in Flutter in a Ubuntu distribution.

Peter Mortensen's user avatar

answered Nov 10, 2019 at 10:27

Ragesh S's user avatar

Ragesh SRagesh S

3,81413 gold badges100 silver badges134 bronze badges

1

It can be directly added by using the following command:

echo 'export PATH=$PATH:/new/directory' >> ~/.zshrc
source ~/.zshrc

abdusco's user avatar

abdusco

8,8802 gold badges27 silver badges41 bronze badges

answered Jul 11, 2016 at 11:31

Anoop Nagabhushan's user avatar

2

One way to add a permanent path, which worked for me, is:

cd /etc/profile.d
touch custom.sh
vi custom.sh 
export PATH=$PATH:/path according to your setting/

Restart your computer and here we go; the path will be there permanently.

Peter Mortensen's user avatar

answered May 28, 2016 at 3:19

user6393373's user avatar

3

Add script file [name_of_script].sh to the /etc/profile.d folder with the line:

export PATH=$PATH:/dir

Every script within the /etc/profile.d folder is automatically executed by /etc/profile on login.

Peter Mortensen's user avatar

answered Apr 10, 2015 at 12:12

Yuriy Vasylenko's user avatar

4

My answer is in reference to the setting up of a Go environment on Ubuntu Linux (amd64). I have faced the same trouble of setting the path of environment variables (GOPATH and GOBIN), losing it on terminal exit and rebuilding it using the source <file_name> every time.

The mistake was to put the path (GOPATH and GOBIN) in ~/.bash_profile file. After wasting a few good hours, I found that the solution was to put GOPATH and GOBIN in the ~/.bash_rc file in the manner:

export GOPATH=$HOME/go
export GOBIN=$GOPATH/bin
export PATH=$PATH:$GOPATH:$GOBIN

And in doing so, the Go installation worked fine and there were no path losses.

The reason with which this issue can be related is that settings for non-login shells, like your Ubuntu terminal or GNOME terminal where we run the Go code, are taken from the ~./bash_rc file and the settings for login shells are taken from ~/.bash_profile file. And from the ~/.profile file if the ~/.bash_profile file is unreachable.

Peter Mortensen's user avatar

answered May 4, 2017 at 21:13

Abhiroj Panwar's user avatar

The files where you add the export command depends on if you are in login-mode or non-login-mode.

If you are in login-mode, the files you are looking for are either /etc/bash or /etc/bash.bashrc.

If you are in non-login-mode, you are looking for the file /.profile or for the files within the directory /.profiles.d

The files mentioned above is where the system variables are.

Peter Mortensen's user avatar

answered Nov 5, 2013 at 13:35

Dikinha's user avatar

3

Permanently add to the PATH variable

Global:

echo "export PATH=$PATH:/new/path/variable" >> /etc/profile

Local (for the current user only):

echo "export PATH=$PATH:/new/path/variable" >> ~/.profile

For global, restart. For local, relogin.

Example

Before:

$ cat /etc/profile

#!/bin/sh

export PATH=/usr/bin:/usr/sbin:/bin:/sbin

After:

$ cat /etc/profile

#!/bin/sh

export PATH=/usr/bin:/usr/sbin:/bin:/sbin
export PATH=/usr/bin:/usr/sbin:/bin:/sbin:/new/path/variable

Alternatively you can just edit file «profile»:

$ cat /etc/profile

#!/bin/sh

export PATH=/usr/bin:/usr/sbin:/bin:/sbin:/new/path/variable

Another way (thanks gniourf_gniourf):

echo 'PATH=$PATH:/new/path/variable' >> /etc/profile

You shouldn’t use double quotes here! echo ‘export
PATH=$PATH:/new/path/variable’… And by the way, the export keyword
is very likely useless as the PATH variable is very likely already
marked as exported. – gniourf_gniourf

Peter Mortensen's user avatar

answered Nov 14, 2014 at 17:35

user3439968's user avatar

user3439968user3439968

3,3181 gold badge17 silver badges15 bronze badges

4

Zues77 has the right idea. The OP didn’t say «How can I hack my way through this?». The OP wanted to know how to permanently append to $PATH:

sudo nano /etc/profile

This is where it is set for everything and is the best place to change it for all things needing $PATH.

Peter Mortensen's user avatar

answered Sep 25, 2015 at 2:26

Joe D's user avatar

Joe DJoe D

391 bronze badge

1

Let’s say you’re running macOS. You have a binary you trust and would like to make available across your system, but don’t necessarily want the directory in which the binary is to be added to your PATH.

You can opt to copy/move the binary to /usr/local/bin, which should already be in your PATH. This will make the binary executable like any other binary you may already have access to in your terminal.

Peter Mortensen's user avatar

answered Jul 4, 2019 at 13:25

Leo's user avatar

LeoLeo

4286 silver badges5 bronze badges

The simplest way is the following line,

PATH="<directory you want to include>:$PATH"

in your .bashrc file in the home directory.

It will not get reset even if you close the terminal or reboot your PC. It’s permanent.

Peter Mortensen's user avatar

answered Oct 18, 2013 at 17:00

Alex Jones's user avatar

Alex JonesAlex Jones

75010 silver badges22 bronze badges

1

This is a one-liner. It adds a line to the .bashrc. That line is going to check if the directory has already been added to the path and append if not. This will prevent duplicating your directory in the path every time you source .bashrc.

echo "[[ ":$PATH:" != *":$(pwd)/path/to/add:"* ]] && export PATH="${PATH:+${PATH}}:$(pwd)/path/to/add"" >> ~/.bashrc

source ~/.bashrc

Peter Mortensen's user avatar

answered Feb 1, 2020 at 11:08

sr9yar's user avatar

sr9yarsr9yar

4,4605 gold badges50 silver badges56 bronze badges

1

I think the most elegant way is:

  1. Add this in the ~./bashrc file:

    if [ -d "new-path" ]; then
      PATH=$PATH:new-path
    fi
    
  2. source *~/.bashrc*

(Ubuntu)

Peter Mortensen's user avatar

answered Jul 17, 2016 at 2:50

Gimcuan Hui's user avatar

1

For a Debian distribution, you have to:

  • edit file ~/.bashrc. E.g: vim ~/.bashrc
  • add export PATH=$PATH:/path/to/dir
  • then restart your computer. Be aware that if you edit file ~/.bashrc as root, your environment variable you added will work only for root

Peter Mortensen's user avatar

answered Dec 27, 2017 at 21:18

onlyme's user avatar

onlymeonlyme

3,6142 gold badges22 silver badges16 bronze badges

2

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

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

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

echo $PATH

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

Для того, чтобы добавить новый путь к переменной PATH, можно воспользоваться командой export. Например, давайте добавим к значению переменной PATH папку/opt/local/bin. Для того, чтобы не перезаписать имеющееся значение переменной PATH новым, нужно именно добавить (дописать) это новое значение к уже имеющемуся, не забыв о разделителе-двоеточии:

export PATH=$PATH:/opt/local/bin

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

echo $PATH

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

В ОС Ubuntu значение переменной PATH содержится в файле /etc/environment, в некоторых других дистрибутивах её также можно найти и в файле /etc/profile. Вы можете открыть файл /etc/environment и вручную дописать туда нужное значение:

sudo vi /etc/environment

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/opt/local/bin"

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

vi ~/.bashrc

export PATH=$PATH:/opt/local/bin

Выводы

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

Creative Commons License

Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .

Об авторе

Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.

Contents

  1. Manipulating environment variables and values

    1. Setting values to environment variables
    2. Examining values of environment variables

      1. Desktop environment specifics
    3. Erasing environment variables
  2. Working principles of environment variables

    1. Process locality
    2. Inheritance
    3. Case sensitivity
  3. Bash’s quick assignment and inheritance trick
  4. Persistent environment variables

    1. Session-wide environment variables

      1. ~/.pam_environment
      2. ~/.profile
      3. Other files
    2. System-wide environment variables

      1. /etc/environment
      2. /etc/profile.d/*.sh
      3. Other files
    3. sudo caveat
    4. Launching desktop application with an environment variable
  5. List of common environment variables

    1. File-location related variables
    2. Locale setting variables

      1. The LANGUAGE priority list
    3. Preferred application variables
    4. Graphical desktop-related variables

      1. Gnome-specific variables
    5. Program execution variables
    6. Compilation and software development related variables
    7. Other environment variables

Environment variables provide a way to influence the behaviour of software on the system. For example, the «LANG» environment variable determines the language in which software programs communicate with the user.

Environment variables consist of names that have values assigned to them. For example, on a typical system in the US we would have the value «en_US.UTF-8» assigned to the «LANG» variable.

The meaning of an environment variable and the format of its value are determined by the application using it. There are quite a few well-known environment variables for which the meaning and the format have been agreed upon and they are used by many applications.

Manipulating environment variables and values

While quite a few graphical system configuration applications actually manipulate environment variables in the background, the command-line allows for maximum flexibility when manipulating environment variables.

Note: The shell techniques explained in the following sections apply to the Bourne Shell family of command line shells, which includes sh, ksh, and bash, which is the default shell shipped with Ubuntu. The commands may be different on other shells such as csh.

Setting values to environment variables

In order to set a value to an existing environment variable, we use an assignment expression. For instance, to set the value of the «LANG» variable to «he_IL.UTF-8», we use the following command:

LANG=he_IL.UTF-8

If we use an assignment expression for a variable that doesn’t exist, the shell will create a shell variable, which is similar to an environment variable but does not influence the behaviour of other applications.

A shell variable can be exported to become an environment variable with the export command. To create the «EDITOR» environment variable and assign the value «nano» to it, you can do:

EDITOR=nano
export EDITOR

The bash shell (the default command-line shell in Ubuntu) provides a shortcut for creating environment variables. The previous example could be performed with the following single command:

export EDITOR=nano

Examining values of environment variables

The printenv command prints the names and values of all currently defined environment variables:

printenv 

To examine the value of a particular variable, we can specify its name to the printenv command:

printenv TERM

Another way to achieve that is to use the dollar sign ($), as used in the following example:

echo $TERM

There is a command for doing temporary, short-term changes to the environment. It can also be used to display the current environment. This command is env.

env

The dollar sign can actually be used to combine the values of environment variables in many shell commands. For example, the following command can be used to list the contents of the «Desktop» directory within the current user’s home directory.

ls $HOME/Desktop

For the sake of completeness: If you want to print the names and values also of the non-exported shell variables, i.e. not only the environment variables, this is one way:

( set -o posix ; set ) | less

Desktop environment specifics

If you use a terminal window to examine environment variables, you actually study the environment variables of the shell that is running in the terminal. Those variables are not necessarily available in the graphical environment of the desktop. To examine the environment variables that are effective when you for instance start an application from the launcher, you can follow the guidance in this Ask Ubuntu answer.

Erasing environment variables

While simply setting an empty value to an environment variable, as shown in the example below, may nullify its effect in most cases, there are a few variables such as «POSIXLY_CORRECT» whose mere existence, even with an empty value, influences the behavior of programs.

export LC_ALL=

The unset command can be used in order to completely erase the existence of an environment variable:

unset LC_ALL

It is also possible to use the «-n» switch to the export command in order to un-export an environment variable and therefore demote it to become a shell variable while preserving its value.

export -n LC_ALL

Working principles of environment variables

A few simple principles govern how environment variables work and achieve their effect.

Process locality

The values of environment variables are local, which means they are specific to the running process in or for which they were set. This means that if we open two terminal windows (which means we have two separate bash processes running), and change a value of an environment variable in one of the windows, that change will not be seen by the shell in the other window or any other program currently on the desktop.

Inheritance

When a parent process creates a child process, for example when we run the «gedit» command from the terminal and «bash» (the parent process) creates «gedit» (the child process), the child process inherits all the environment variables and values the parent process had.

This means that if we set a new value to the «LANG» environment variable in the terminal, and then run «gedit» from that same terminal, «gedit» will inherit the new value of «LANG», and therefore may display in a different language than the rest of the processes on the desktop. (See The LANGUAGE priority list, though.)

Note that because of the Process Locality principle explained above, once we run Gedit, changes to environment variables of the parent process will not be seen by the child process and vice-versa.

Note: in the Gnome graphical desktop environment, gnome-session is the parent process of all the processes running on the desktop. This fact (along with the Inheritance principle) is the key to our ability to powerfully influence the operation of our desktop with environment variables. The equivalent process in KDE is kde-session.

Case sensitivity

The names of environment variables are case sensitive. This means that lang is not the same variable as LANG, Lang, or laNg.

It is a common practice to name all environment variables with only English capital letters and underscore (_) signs.

Bash’s quick assignment and inheritance trick

The bash shell has a trick to allow us to set one or more environment variables and run a child process with single command. For example, in order to set the «LANGUAGE» and «FOO» environment variables and then run «gedit», we would use the following command:

LANGUAGE=he FOO=bar gedit

Note: When using this command, the new values are only assigned to the environment variables of the child process (in this case gedit). The variables of the shell retain their original values. For instance, in the example above, the value of «LANGUAGE» will not change from its original value, as far as subsequent commands to the shell are concerned.

A similar behaviour can be achieved with other shells by using the env command.

Persistent environment variables

So far we’ve only discussed ways set an environment variable value temporarily until the shell session in which it was set is closed. One may wonder if there is a way to somehow permanently set an environment variable to a certain value.

Session-wide environment variables

Suitable files for environment variable settings that should affect just a particular user (rather than the system as a whole) are ~/.pam_environment and ~/.profile. After having edited one of those files, you should re-login in order to initialize the variables.

~/.pam_environment

This file is specifically meant for setting a user’s environment. It is not a script file, but rather consists of assignment expressions, one per line. This example sets the variable FOO to a literal string and modifies the PATH variable:

FOO=bar
PATH DEFAULT=${PATH}:/home/@{PAM_USER}/MyPrograms

Note:

  • When doing a simple variable assignment like the FOO=bar example, quotes have not special meaning. This means that values cannot contain spaces.

  • The syntax used for modifying PATH, which differs from the syntax of shell script files, is required for variable expansion to work. Some variables, like HOME, might not be set at the time ~/.pam_environment is parsed. See /etc/security/pam_env.conf for more details.

  • ~/.pam_environment is written to when you use various GUIs to set the language or regional formats. Consequently, if you for instance set LC_TIME by editing ~/.pam_environment manually, your entry will be overwritten if you afterwards use the Language Support GUI to change the regional formats setting.

~/.profile

In this file you can also place environment variable assignments, since it gets executed automatically by the DisplayManager during the start-up process desktop session as well as by the login shell when one logs in from the textual console. This is a ~/.profile equivalent of the above example:

export FOO=bar
export PATH="$PATH:$HOME/MyPrograms"

Note: The code in ~/.profile is run after ~/.pam_environment has been read. That makes ~/.profile suitable to use if you want to override a locale related variable that was set in ~/.pam_environment via e.g. Language Support.

Other files

If you are using KDE, see also the KDE User-base page on this topic.

Shell config files such as ~/.bashrc, ~/.bash_profile, and ~/.bash_login are often suggested for setting environment variables. While this may work on Bash shells for programs started from the shell, variables set in those files are not available by default to programs started from the graphical environment in a desktop session.

System-wide environment variables

A suitable file for environment variable settings that affect the system as a whole (rather than just a particular user) is /etc/environment. An alternative is to create a file for the purpose in the /etc/profile.d directory.

/etc/environment

This file is specifically meant for system-wide environment variable settings. It is not a script file, but rather consists of assignment expressions, one per line.

FOO=bar

Note: Variable expansion does not work in /etc/environment.

/etc/profile.d/*.sh

Files with the .sh extension in the /etc/profile.d directory get executed whenever a bash login shell is entered (e.g. when logging in from the console or over ssh), as well as by the DisplayManager when the desktop session loads.

You can for instance create the file /etc/profile.d/myenvvars.sh and set variables like this:

export JAVA_HOME=/usr/lib/jvm/jdk1.7.0
export PATH=$PATH:$JAVA_HOME/bin

Other files

While /etc/profile is often suggested for setting environment variables system-wide, it is a configuration file of the base-files package, so it’s not appropriate to edit that file directly. Use a file in /etc/profile.d instead as shown above. (Files in /etc/profile.d are sourced by /etc/profile.)

/etc/default/locale is specifically meant for system-wide locale environment variable settings. It’s written to by the installer and when you use Language Support to set the language or regional formats system-wide. On a desktop system there is normally no reason to edit this file manually.

The shell config file /etc/bash.bashrc is sometimes suggested for setting environment variables system-wide. While this may work on Bash shells for programs started from the shell, variables set in that file are not available by default to programs started from the graphical environment in a desktop session.

sudo caveat

Any variables added to these locations will not be reflected when invoking them with a sudo command, as sudo has a default policy of resetting the Environment and setting a secure path (this behavior is defined in /etc/sudoers). As a workaround, you can use sudo su that will provide a shell with root privileges but retaining any modified PATH variables. Alternatively you can setup sudo not to reset certain environment variables by adding some explicit environment settings to keep in /etc/sudoers:

  • Run sudo visudo

  • Add the following to the bottom:
Defaults env_keep += "http_proxy SOMEOTHERVARIABLES ANOTHERVARIABLE ETC"

Launching desktop application with an environment variable

You can add an environment variable to an application by editing its .desktop file. For example, to run «digiKam» with the environment variable APPMENU_DISPLAY_BOTH=1, find the corresponding digikam.desktop file and add the setting of the variable, via the env command, to the entry «Exec»:

Exec=env APPMENU_DISPLAY_BOTH=1 digikam -caption "%c" %i

List of common environment variables

Each application is free to define and use its own environment variables. Many manual pages include long lists of environment variables that can affect the behaviour of the application they describe. However, the most useful variables are common to many applications.

The following variables determine how the system locates various files in order to operate.

Variable

Value Examples

What it’s for

PATH

/usr/sbin:/usr/bin:/sbin:/bin

When you type a command to run, the system looks for it in the directories specified by PATH in the order specified

MANPATH

/usr/share/man:/usr/local/man

List of directories for the system to search manual pages in

LD_LIBRARY_PATH

/opt/app/oracle/lib

List of directories where the system searches for runtime libraries in addition to those hard-defined by ld and in /etc/ld.so.conf.d/*.conf files. Note: You can only set this environment variable inside an interactive shell. Since Ubuntu 9.04 Jaunty Jackalope, LD_LIBRARY_PATH cannot be set in $HOME/.profile, /etc/profile, nor /etc/environment files. You must use /etc/ld.so.conf.d/*.conf configuration files. See Launchpad bug #366728 for more information.

TMPDIR

/var/tmp

The directory used for temporary file creation by several programs

Locale setting variables

The following environment variables determine the locale-related behaviour of the systems such as the language of displayed messages and the way times and dates are presented.

The values that can be assigned to the locale environment variables are names of locales generated on the system. To see which locales have been generated, one can use the locale -a command.

When you install a language in Ubuntu using Language Support, locales for that language are generated automatically. Otherwise locales can be generated with the locale-gen command.

Variable

What it’s for

LANG

The basic language setting used by applications on the system, unless overridden by one of the other locale environment variables

LC_CTYPE

The character set used to display and input text

LC_NUMERIC

How non-monetary numeric values are formatted on screen

LC_TIME

How date and time values are formatted

LC_COLLATE

How to sort various information items (e.g. defines the order of the alphabet so items can be ordered alphabetically by the sort command)

LC_MONETARY

How monetary numeric values are formatted

LC_MESSAGES

Which language is to display messages to the end user

LC_PAPER

Definitions of paper formats and standards

LC_NAME

How names are formatted

LC_ADDRESS

How to display address information

LC_TELEPHONE

How telephone numbers are structured

LC_MEASUREMENT

What units of measurement are used

LC_IDENTIFICATION

Metadata about the locale information

LC_ALL

This variable serves as a powerful override over all the other locale environment variables. When its value is set, applications use that value to determine which locale settings to use regardless of the values of the other variables.
Note: Do not set this variable persistently on a desktop system. If you do, you effectively disable the GUIs for controlling language and locales.

By utilizing various combinations of settings for the locale variables, you can make interesting tweaks to the behaviour of your system. For example, you can make your system display message in US-English while using number, date, and measurement formats that are more common to European countries. The Language Support GUI makes that distinction by design.

The locale variables can effectively override each other’s value in some combinations. Therefore examining the values of the variables themselves may not always provide clear indication of how the system will behave. The locale command can be used to examine what the effective values are to the applications.

The LANGUAGE priority list

The «LANGUAGE» environment variable, which is set by the GUIs more often than not on Ubuntu desktops, controls language for message and menu display for GNU compatible applications. For such applications it overrides whatever locale names are set in «LANG» and «LC_MESSAGES».

Unlike «LANG» and «LC_*», «LANGUAGE» should not be assigned a complete locale name including the encoding part (e.g. «.UTF-8»). Instead «LANGUAGE» should contain a colon separated priority list of language codes, for instance «es:de:en». A single language code is also correct.

Preferred application variables

These environment variables indicate to various programs what the user’s preferred applications are for performing certain tasks.

These variables are typically not respected by GUI applications that tend to include their own built-in text display windows and editors. Most desktop environments also contain their own preferred application selection system.

Variable

Value Examples

What it’s for

PAGER

/usr/bin/less

The name of the utility used to display long text by commands such as man.

EDITOR

/usr/bin/nano

The name of the user’s preferred text editor. Used by programs such as the mutt mail client and sudoedit.

VISUAL

/usr/bin/gedit

Similar to the «EDITOR» environment variable, applications typically try the value in this variable first before falling back to «EDITOR» if it isn’t set.

BROWSER

/usr/bin/lynx

The name of the user’s preferred web browser. This variable is arguably less common than the rest

Variable

Value Examples

What it’s for

DISPLAY

:0.0
localhost:10.0
terminal01:0.0

This variable is used to indicate to graphical applications where to display the actual graphical user interface, the value consists of 3 parts: A host-name followed by a colon (:), a display number followed by a dot (.) and a screen number. The host-name part can be used to have the graphical output sent to a remote machine over the network. It can be omitted when the output is meant for an X server running on the local machine. The display number allows selecting among multiple X servers running on the same machine (Ubuntu uses multiple X servers to enable multiple graphical desktop sessions). Although the screen number is used to select among multiple physical screen that are managed by the same X server, it is rarely set to anything other than «0» nowadays. Manually setting the «DISPLAY» environment variable’s value is rarely needed nowadays since it can be automatically and intelligently adjusted by many applications such as «GDM» and «SSH» when needed.

XDG_DATA_HOME

~/.local/share

Indicates to applications that conform to the freedesktop.org specifications, where to place the user’s private data. This variable is typically unset since a sensible default fall-back value was defined by the specifications.

XDG_CONFIG_HOME

~/.config

Indicates to applications that conform to the freedesktop.org specifications, where to place the user’s configuration information. This variable is typically unset since a sensible default fall-back value was defined by the specifications.

XDG_DATA_DIRS

/usr/local/share:/usr/share

A colon-separated list (similar to «PATH») of directories where data is searched for by applications that conform to the freedesktop.org specifications. This variable is typically unset since a sensible default fall-back value was defined by the specifications.

XDG_CONFIG_DIRS

/etc/xdg

A colon-separated list (similar to «PATH») of directories where configuration information is searched for by applications that conform to the freedesktop.org specifications. This variable is typically unset since a sensible default fall-back value was defined by the specifications.

XDG_CACHE_HOME

~/.cache

A location used by applications that conform to the freedesktop.org specifications to cache temporary data. This variable is typically unset since a sensible default fall-back value was defined by the specifications.

Gnome-specific variables

Variable

Value Examples

What it’s for

NAUTILUS_SCRIPT_SELECTED_FILE_PATHS

/home/ifireball/about.html

This environment variable is set by Nautilus, the Gnome file manager, to a newline-delimited list of the currently selected files, when a script is invoked from the right-click menu. This variable is only set if the files are local, e.g. not from a network share or an SSH connection

NAUTILUS_SCRIPT_SELECTED_URIS

file:///home/ifireball/about.html

This environment variable is set by Nautilus to a newline-delimited list of the URI addresses of the currently selected files, when a script is invoked from the right-click menu.

NAUTILUS_SCRIPT_CURRENT_URI

file:///home/ifireball

This environment variable is set to the URI address of the location currently displayed by the Nautilus window, when a script is invoked from the right-click menu.

NAUTILUS_SCRIPT_WINDOW_GEOMETRY

828×511+251+342

This environment variable is set to the on-screen position of the Nautilus window, when a script is invoked from the right-click menu.

Program execution variables

Arguably the most powerful (but dangerous) environment variables, the following allow tweaking the basic way software actually runs.

Variable

Value Examples

What it’s for

LD_PRELOAD

/usr/lib/valgrind.so

This variable can be used to inject a custom dynamic library into an application’s memory when it loads. It can be used to do things like replacing the application’s built-in memory allocation library with a debugging version in order to detect memory leaks. It can also be used to override the way it does various things like play sounds.

Variable

Value Examples

What it’s for

CC

gcc

The name of the C compiler to use

CXX

g++

The name of the C++ compiler to use

CFLAGS

-o out.o

A list of debugging/optimization flags to pass to the C compiler

CXXFLAGS

-Wall

A list of debugging/optimization flags to pass to the C++ compiler

CPPFLAGS

-DDEBUG

A list of flags to pass to the C/C++ pre-processor/compiler

LIBRARY_PATH

/usr/lib/firefox

A list of directories (separated by colons) in which library files should be searched for

INCLUDE

/opt/app/src/include

A colon-separated list of directories in which header files should be searched for

CPATH

..:$HOME/include:/usr/local/include

A colon-separated list of directories in which header files should be searched for

Other environment variables

Variable

Value Examples

What it’s for

USER

myuser1

The name of the currently logged-in user. This variable is set by the system. You probably shouldn’t change its value manually.

LOGNAME

myuser1

Similar to «USER», some programs prefer to read this variable rather than USER.

HOME

/home/myuser1

The location of the currently logged-in user’s home directory.

PWD

/home/myuser1/Desktop

The current working directory of the shell.

SHELL

/bin/bash

The user’s preferred command-line shell as it is set in the /etc/passwd file.

POSIXLY_CORRECT

N/A

If this environment variable exists, regardless of its value, it causes the behaviour of quite a few utilities to more closely match the behaviour defined by the POSIX standard. This typically makes various GNU extensions that make life easier not work, but it may just be what’s needed to make an old UNIX script execute successfully.

HOSTALIASES

/etc/host.aliases

The name of a file containing host-name aliases for use with various network programs.

TZDIR

/usr/share/zoneinfo

The path of the directory containing time-zone information files. This typically does not need to be set manually, as the system searches for such files in /usr/share/zoneinfo by default.

TZ

IST-2
:Japan

This variable was used by older UNIX systems to specify the system’s time-zone. However, Ubuntu and most other modern systems use the /etc/localtime file for that purpose. This variable can, however, be used to make one user’s particular session display times in a different time-zone than the rest of the system.
The value of this variable can either be the name and offset of a time-zone (as seen in the first example) or the name of a zone-info file in /usr/share/zoneinfo (as seen in the second example).

TERM

xterm

The name of a terminal information file from /lib/terminfo, this file instructs terminal programs how to achieve things such as displaying color. It may help to fiddle with this variable if you’re trying use an odd terminal emulator program or trying to connect a hardware serial-port terminal emulator and getting undesired results.

TERMCAP

This variable can be used instead of «TERM» to manually specify terminal information rather than point to a file.

COLUMNS

80

The number of text columns in the terminal window. Try adjusting this variable if lines don’t seem to wrap properly in the console.

LINES

25

The number of text lines on the console window. Try adjusting this variable if you’re getting strange results when scrolling text.

SDL_VIDEO_FULLSCREEN_DISPLAY

0

In multiple monitor setups, such as Xinerama or TwinView, this sets which screen to use for full-screen mode for SDL applications/games. If unset all screens are used.


CategoryX CategoryCommandLine


Download Article


Download Article

Operating systems commonly use environment variables to define various global settings for parts of your operating system or to control how applications run. The PATH variable is one of these environment variables and is constantly used without the user realizing it. The variable stores a list of directories where applications (most commonly, your shell) should look for a program whenever you run it as a command.

Steps

  1. Image titled Change the Path Variable in Linux Step 1

    1

    Find the current path by typing «echo $PATH» at the bash shell prompt. A list of directories will be provided such as in the example below:

    • uzair@linux:~$ echo $PATH/home/uzair/bin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/games
    • Note: Linux $PATH responds with «:» separators between entries.
  2. Image titled Change the Path Variable in Linux Step 2

    2

    Temporarily add the :/sbin and :/usr/sbin paths to the current path list by typing the following command at the bash shell prompt:

    • uzair@linux:~$ export PATH=$PATH:/sbin/:/usr/sbin/

    Advertisement

  3. Image titled Change the Path Variable in Linux Step 3

    3

    Echo the contents of PATH to confirm the changes are reflected in the variable.

    • uzair@linux:~$ echo $PATH/home/uzair/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
    • Remember, the above is only temporary and will be lost at reboot.
  4. Image titled Change the Path Variable in Linux Step 4

    4

    Test application program operation with the temporary path to assure the all works well.

  5. Image titled Change the Path Variable in Linux Step 5

    5

    Permanently change the path setting by adding the same line to your ~/.bashrc file

  6. Advertisement

Add New Question

  • Question

    What would I use to redefine existing system variable PATH?

    Community Answer

    To change the PATH variable, type export PATH=»$PATH:/path/to/new/executable/directory». Or, if you want to make it permanent, edit the .bashrc to say something like this: # what this location has
    export PATH=»$PATH:/path/to/new/executable/directory»

Ask a Question

200 characters left

Include your email address to get a message when this question is answered.

Submit

Advertisement

Video

Thanks for submitting a tip for review!

  • Changing your PATH variable can potentially cause your operating system to not work properly. Operating system and application programs commonly refer to the path variable to find files. If the variable is not configured properly, programs will not run or run incorrectly. ALWAYS TEST the temporary setting using the method described above BEFORE STORING the new path permanently in your ~/.bashrc.

Advertisement

About This Article

Thanks to all authors for creating a page that has been read 219,025 times.

Is this article up to date?


Download Article


Download Article

Operating systems commonly use environment variables to define various global settings for parts of your operating system or to control how applications run. The PATH variable is one of these environment variables and is constantly used without the user realizing it. The variable stores a list of directories where applications (most commonly, your shell) should look for a program whenever you run it as a command.

Steps

  1. Image titled Change the Path Variable in Linux Step 1

    1

    Find the current path by typing «echo $PATH» at the bash shell prompt. A list of directories will be provided such as in the example below:

    • uzair@linux:~$ echo $PATH/home/uzair/bin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/games
    • Note: Linux $PATH responds with «:» separators between entries.
  2. Image titled Change the Path Variable in Linux Step 2

    2

    Temporarily add the :/sbin and :/usr/sbin paths to the current path list by typing the following command at the bash shell prompt:

    • uzair@linux:~$ export PATH=$PATH:/sbin/:/usr/sbin/

    Advertisement

  3. Image titled Change the Path Variable in Linux Step 3

    3

    Echo the contents of PATH to confirm the changes are reflected in the variable.

    • uzair@linux:~$ echo $PATH/home/uzair/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
    • Remember, the above is only temporary and will be lost at reboot.
  4. Image titled Change the Path Variable in Linux Step 4

    4

    Test application program operation with the temporary path to assure the all works well.

  5. Image titled Change the Path Variable in Linux Step 5

    5

    Permanently change the path setting by adding the same line to your ~/.bashrc file

  6. Advertisement

Add New Question

  • Question

    What would I use to redefine existing system variable PATH?

    Community Answer

    To change the PATH variable, type export PATH=»$PATH:/path/to/new/executable/directory». Or, if you want to make it permanent, edit the .bashrc to say something like this: # what this location has
    export PATH=»$PATH:/path/to/new/executable/directory»

Ask a Question

200 characters left

Include your email address to get a message when this question is answered.

Submit

Advertisement

Video

Thanks for submitting a tip for review!

  • Changing your PATH variable can potentially cause your operating system to not work properly. Operating system and application programs commonly refer to the path variable to find files. If the variable is not configured properly, programs will not run or run incorrectly. ALWAYS TEST the temporary setting using the method described above BEFORE STORING the new path permanently in your ~/.bashrc.

Advertisement

About This Article

Thanks to all authors for creating a page that has been read 219,025 times.

Is this article up to date?

On Linux, how can I add a directory to the $PATH so it remains persistent across different sessions?

Background

I’m trying to add a directory to my path so it will always be in my Linux path. I’ve tried:

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

This works, however each time I exit the terminal and start a new terminal instance, this path is lost, and I need to run the export command again.

How can I do it so this will be set permanently?

Amin's user avatar

Amin

1,3351 gold badge17 silver badges29 bronze badges

asked Feb 1, 2013 at 0:57

Ali's user avatar

1

You need to add it to your ~/.profile or ~/.bashrc file. 

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

Depending on what you’re doing, you also may want to symlink to binaries:

cd /usr/bin
sudo ln -s /path/to/binary binary-name

Note that this will not automatically update your path for the remainder of the session. To do this, you should run:

source ~/.profile 
or
source ~/.bashrc

Greenbeard's user avatar

answered Feb 1, 2013 at 1:01

mpowered's user avatar

mpoweredmpowered

12.9k2 gold badges15 silver badges18 bronze badges

26

There are multiple ways to do it. The actual solution depends on the purpose.

The variable values are usually stored in either a list of assignments or a shell script that is run at the start of the system or user session. In case of the shell script you must use a specific shell syntax and export or set commands.

System wide

  1. /etc/environment List of unique assignments. Allows references. Perfect for adding system-wide directories like /usr/local/something/bin to PATH variable or defining JAVA_HOME. Used by PAM and systemd.

  2. /etc/environment.d/*.conf List of unique assignments. Allows references. Perfect for adding system-wide directories like /usr/local/something/bin to PATH variable or defining JAVA_HOME. The configuration can be split into multiple files, usually one per each tool (Java, Go, and Node.js). Used by systemd that by design do not pass those values to user login shells.

  3. /etc/xprofile Shell script executed while starting X Window System session. This is run for every user that logs into X Window System. It is a good choice for PATH entries that are valid for every user like /usr/local/something/bin. The file is included by other script so use POSIX shell syntax not the syntax of your user shell.

  4. /etc/profile and /etc/profile.d/* Shell script. This is a good choice for shell-only systems. Those files are read only by shells in login mode.

  5. /etc/<shell>.<shell>rc. Shell script. This is a poor choice because it is single shell specific. Used in non-login mode.

User session

  1. ~/.pam_environment. List of unique assignments, no references allowed. Loaded by PAM at the start of every user session irrelevant if it is an X Window System session or shell. You cannot reference other variables including HOME or PATH so it has limited use. Used by PAM.

  2. ~/.xprofile Shell script. This is executed when the user logs into X Window System system. The variables defined here are visible to every X application. Perfect choice for extending PATH with values such as ~/bin or ~/go/bin or defining user specific GOPATH or NPM_HOME. The file is included by other script so use POSIX shell syntax not the syntax of your user shell. Your graphical text editor or IDE started by shortcut will see those values.

  3. ~/.profile, ~/.<shell>_profile, ~/.<shell>_login Shell script. It will be visible only for programs started from terminal or terminal emulator. It is a good choice for shell-only systems. Used by shells in login mode.

  4. ~/.<shell>rc. Shell script. This is a poor choice because it is single shell specific. Used by shells in non-login mode.

Notes

GNOME on Wayland starts a user login shell to get the environment. It effectively uses the login shell configurations ~/.profile, ~/.<shell>_profile, ~/.<shell>_login files.

Man pages

  • environment
  • environment.d https://linux.die.net/man/1/environment.d
  • bash
  • dash

Distribution-specific documentation

  • Ubuntu
  • Arch Linux

Difference between Login Shell and Non-Login Shell?

Peter Mortensen's user avatar

answered Nov 16, 2014 at 21:29

Grzegorz Żur's user avatar

Grzegorz ŻurGrzegorz Żur

46.3k14 gold badges111 silver badges103 bronze badges

11

In Ubuntu, edit /etc/environment. Its sole purpose is to store environment variables. Originally the $PATH variable is defined here.

This is a paste from my /etc/environment file:

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

So you can just open up this file as root and add whatever you want.

For immediate results,

Run (try as normal user and root):

source /etc/environment && export PATH

If you use Z shell (zsh), add this line right after the comments in /etc/zsh/zshenv file:

source /etc/environment

I encountered this little quirk on Ubuntu 15.10 (Wily Werewolf), but if your zsh is not getting the correct PATH, this could be why.

answered May 27, 2014 at 16:27

trve.fahad's user avatar

trve.fahadtrve.fahad

4,3492 gold badges16 silver badges25 bronze badges

13

For Bash, you can put the export declaration in ~/.bashrc. For example, my .bashrc contains this line:

export PATH=/var/lib/gems/1.8/bin:/home/ash/.bin:$PATH

answered Feb 1, 2013 at 0:59

ashastral's user avatar

ashastralashastral

2,7981 gold badge20 silver badges32 bronze badges

10

You may set $PATH permanently in two ways.

  1. To set the path for a particular user:

    You may need to make the entry in file .bash_profile in the home directory for the user.

    E.g, in my case I will set the java path in the Tomcat user profile*

     echo "export PATH=$PATH:/path/to/dir" >> /home/tomcat/.bash_profile
    
  2. To set a common path for all system users, you may need to set the path like this:

     echo "export PATH=$PATH:/path/to/dir" >> /etc/profile
    

Peter Mortensen's user avatar

answered Jan 3, 2014 at 11:35

Mohit M's user avatar

Mohit MMohit M

7497 silver badges15 bronze badges

3

You can use on CentOS or Red Hat Linux (RHEL) for the local user:

echo $"export PATH=$PATH:$(pwd)" >> ~/.bash_profile

This adds the current directory (or you can use another directory) to the PATH. This makes it permanent, but it takes effect at the next user logon.

If you don’t want do a re-logon, then you can use:

source ~/.bash_profile

That reloads the # User specific environment and startup programs. This comment is present in file .bash_profile.

Peter Mortensen's user avatar

answered Oct 21, 2016 at 4:11

Daniel Antonio Nuñez Carhuayo's user avatar

You can also set it permanently, editing one of these files:

/etc/profile (for all users)

~/.bash_profile (for current user)

~/.bash_login (for current user)

~/.profile (for current user)

You can also use /etc/environment to set a permanent PATH environment variable, but it does not support variable expansion.

Extracted from: Linux: Añadir ruta al PATH

Peter Mortensen's user avatar

answered Jun 29, 2016 at 8:59

Delucaramos's user avatar

1

I think the most elegant way is:

  1. Add this in the ~/.bashrc file.

    Run this command:

     gedit ~/.bashrc
    

    Add your path inside it:

     export PATH=$PATH:/opt/node/bin
    
  2. source ~/.bashrc

(Ubuntu)

Peter Mortensen's user avatar

answered Nov 4, 2017 at 13:40

Himanshu sharma's user avatar

Himanshu sharmaHimanshu sharma

7,2494 gold badges42 silver badges74 bronze badges

1

  1. Modify the «/etc/profile» file:

    vi /etc/profile
    

    Press the I key to enter editing mode and move the cursor to the end of the file. Additional entries:

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

    Press the Esc key to exit edit mode, and :wq to save the file.

  2. Make the configuration effective

    source /etc/profile
    

    Explanation:

    The profile file works for all users. If you want it to be valid only for the active user, change the «.bashrc» file.

Peter Mortensen's user avatar

answered Nov 23, 2018 at 9:24

Jia's user avatar

JiaJia

3343 silver badges4 bronze badges

I stumbled across this question yesterday when searching for a way to add a folder containing my own scripts to the PATH — and was surprised to find out that my own ~/.profile file (on Linux Mint 18.1) already contained this:

# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
    PATH="$HOME/bin:$PATH"
fi

Thus, all I had to do was create the folder ~/bin and put my scripts there.

Peter Mortensen's user avatar

answered Mar 4, 2017 at 11:09

RobertG's user avatar

RobertGRobertG

1,4151 gold badge20 silver badges41 bronze badges

2

You can add that line to your console configuration files (e.g., .bashrc, or to .profile).

Peter Mortensen's user avatar

answered Feb 1, 2013 at 0:59

aqua's user avatar

aquaaqua

3,15928 silver badges40 bronze badges

3

After so much research, I found a simple solution for this (I am using Elementary OS), inspired by Flutter – Step by Step Installation on Linux – Ubuntu.

Run the following command to open the .bashrc file in edit mode. (You
may also use vi or any other editor).

~$ sudo nano ~/.bashrc

Add the following line at the end of the file and save.

export PATH="[FLUTTER_SDK_PATH]/flutter/bin:$PATH"

For example:

export PATH="/home/rageshl/dev/flutter/bin:$PATH"

enter image description here

I believe this is the permanent solution for setting the path in Flutter in a Ubuntu distribution.

Peter Mortensen's user avatar

answered Nov 10, 2019 at 10:27

Ragesh S's user avatar

Ragesh SRagesh S

3,81413 gold badges100 silver badges134 bronze badges

1

It can be directly added by using the following command:

echo 'export PATH=$PATH:/new/directory' >> ~/.zshrc
source ~/.zshrc

abdusco's user avatar

abdusco

8,8802 gold badges27 silver badges41 bronze badges

answered Jul 11, 2016 at 11:31

Anoop Nagabhushan's user avatar

2

One way to add a permanent path, which worked for me, is:

cd /etc/profile.d
touch custom.sh
vi custom.sh 
export PATH=$PATH:/path according to your setting/

Restart your computer and here we go; the path will be there permanently.

Peter Mortensen's user avatar

answered May 28, 2016 at 3:19

user6393373's user avatar

3

Add script file [name_of_script].sh to the /etc/profile.d folder with the line:

export PATH=$PATH:/dir

Every script within the /etc/profile.d folder is automatically executed by /etc/profile on login.

Peter Mortensen's user avatar

answered Apr 10, 2015 at 12:12

Yuriy Vasylenko's user avatar

4

My answer is in reference to the setting up of a Go environment on Ubuntu Linux (amd64). I have faced the same trouble of setting the path of environment variables (GOPATH and GOBIN), losing it on terminal exit and rebuilding it using the source <file_name> every time.

The mistake was to put the path (GOPATH and GOBIN) in ~/.bash_profile file. After wasting a few good hours, I found that the solution was to put GOPATH and GOBIN in the ~/.bash_rc file in the manner:

export GOPATH=$HOME/go
export GOBIN=$GOPATH/bin
export PATH=$PATH:$GOPATH:$GOBIN

And in doing so, the Go installation worked fine and there were no path losses.

The reason with which this issue can be related is that settings for non-login shells, like your Ubuntu terminal or GNOME terminal where we run the Go code, are taken from the ~./bash_rc file and the settings for login shells are taken from ~/.bash_profile file. And from the ~/.profile file if the ~/.bash_profile file is unreachable.

Peter Mortensen's user avatar

answered May 4, 2017 at 21:13

Abhiroj Panwar's user avatar

The files where you add the export command depends on if you are in login-mode or non-login-mode.

If you are in login-mode, the files you are looking for are either /etc/bash or /etc/bash.bashrc.

If you are in non-login-mode, you are looking for the file /.profile or for the files within the directory /.profiles.d

The files mentioned above is where the system variables are.

Peter Mortensen's user avatar

answered Nov 5, 2013 at 13:35

Dikinha's user avatar

3

Permanently add to the PATH variable

Global:

echo "export PATH=$PATH:/new/path/variable" >> /etc/profile

Local (for the current user only):

echo "export PATH=$PATH:/new/path/variable" >> ~/.profile

For global, restart. For local, relogin.

Example

Before:

$ cat /etc/profile

#!/bin/sh

export PATH=/usr/bin:/usr/sbin:/bin:/sbin

After:

$ cat /etc/profile

#!/bin/sh

export PATH=/usr/bin:/usr/sbin:/bin:/sbin
export PATH=/usr/bin:/usr/sbin:/bin:/sbin:/new/path/variable

Alternatively you can just edit file «profile»:

$ cat /etc/profile

#!/bin/sh

export PATH=/usr/bin:/usr/sbin:/bin:/sbin:/new/path/variable

Another way (thanks gniourf_gniourf):

echo 'PATH=$PATH:/new/path/variable' >> /etc/profile

You shouldn’t use double quotes here! echo ‘export
PATH=$PATH:/new/path/variable’… And by the way, the export keyword
is very likely useless as the PATH variable is very likely already
marked as exported. – gniourf_gniourf

Peter Mortensen's user avatar

answered Nov 14, 2014 at 17:35

user3439968's user avatar

user3439968user3439968

3,3181 gold badge17 silver badges15 bronze badges

4

Zues77 has the right idea. The OP didn’t say «How can I hack my way through this?». The OP wanted to know how to permanently append to $PATH:

sudo nano /etc/profile

This is where it is set for everything and is the best place to change it for all things needing $PATH.

Peter Mortensen's user avatar

answered Sep 25, 2015 at 2:26

Joe D's user avatar

Joe DJoe D

391 bronze badge

1

Let’s say you’re running macOS. You have a binary you trust and would like to make available across your system, but don’t necessarily want the directory in which the binary is to be added to your PATH.

You can opt to copy/move the binary to /usr/local/bin, which should already be in your PATH. This will make the binary executable like any other binary you may already have access to in your terminal.

Peter Mortensen's user avatar

answered Jul 4, 2019 at 13:25

Leo's user avatar

LeoLeo

4286 silver badges5 bronze badges

The simplest way is the following line,

PATH="<directory you want to include>:$PATH"

in your .bashrc file in the home directory.

It will not get reset even if you close the terminal or reboot your PC. It’s permanent.

Peter Mortensen's user avatar

answered Oct 18, 2013 at 17:00

Alex Jones's user avatar

Alex JonesAlex Jones

75010 silver badges22 bronze badges

1

This is a one-liner. It adds a line to the .bashrc. That line is going to check if the directory has already been added to the path and append if not. This will prevent duplicating your directory in the path every time you source .bashrc.

echo "[[ ":$PATH:" != *":$(pwd)/path/to/add:"* ]] && export PATH="${PATH:+${PATH}}:$(pwd)/path/to/add"" >> ~/.bashrc

source ~/.bashrc

Peter Mortensen's user avatar

answered Feb 1, 2020 at 11:08

sr9yar's user avatar

sr9yarsr9yar

4,4605 gold badges50 silver badges56 bronze badges

1

I think the most elegant way is:

  1. Add this in the ~./bashrc file:

    if [ -d "new-path" ]; then
      PATH=$PATH:new-path
    fi
    
  2. source *~/.bashrc*

(Ubuntu)

Peter Mortensen's user avatar

answered Jul 17, 2016 at 2:50

Gimcuan Hui's user avatar

1

For a Debian distribution, you have to:

  • edit file ~/.bashrc. E.g: vim ~/.bashrc
  • add export PATH=$PATH:/path/to/dir
  • then restart your computer. Be aware that if you edit file ~/.bashrc as root, your environment variable you added will work only for root

Peter Mortensen's user avatar

answered Dec 27, 2017 at 21:18

onlyme's user avatar

onlymeonlyme

3,6142 gold badges22 silver badges16 bronze badges

2

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Как изменить пароль электронной почты на телефоне mail ru
  • Как изменить переменную css через js
  • Как изменить пароль электронной почты на смартфоне
  • Как изменить переменное напряжение на постоянное
  • Как изменить пароль электронной подписи на госуслугах

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии