How to set environment variable in Linux permanently

19,484

Solution 1

with all the respect due to answers above, setting environnement variables is depending if you want to set to the user session or super user session.

1) input this command in the environement of your choice :

 $ ls -a

2) you will see all the cached files and between them: .bashrc

3) open this file in your favorite editor, for example :

 $ nano .bashrc

4) then add at the end of the file your personnalized variable as following:

 export YOURVARIABLE="/home/"$USER"/YOURPATHFOREXAMPLE"

5) then save and close and open the terminal, check if your variable has been set:

$ echo $YOURVARIABLE
[output ->] /home/the-user-name/YOURPATHFOREXAMPLE

Solution 2

there's a good explanation of when to put it where here : http://www.linuxfromscratch.org/blfs/view/6.3/postlfs/profile.html if you don't have root access put it somewhere local like .bash_profile or depending on which shell you use. Find your shell by typing the command ps .

Solution 3

The usual place is ~/.bashrc assuming that you're using bash, which is the default in most distributions. Check yourself with echo $SHELL. You may use ~/.bash_profile, if you only want to set the variable in login shells (but i.e. not in scripts).

Solution 4

Solution: In order to export and keep environment variables persistent on linux you should export variables decelration into one of the following files: ~/.bash_profile / ~/. bash_login / ~/.profile.

When bash is invoked as an interactive/non-interactive login shell, it first reads and executes commands from the file /etc/profile (if exists) and after looks for these following files ( in that order and do the same) ~/.bash_profile, ~/. bash_login, ~/.profile.

Example: adding secret token into my user profile.

cat << End >> ~/.profile
export SECRET_TOKEN=abc123!@#
End

output:

echo $SECRET_TOKEN
abc123!@#
Share:
19,484
Sylvia Lobo
Author by

Sylvia Lobo

Updated on June 15, 2022

Comments

  • Sylvia Lobo
    Sylvia Lobo almost 2 years

    How I can set the new environment variables and their value permanently in Linux

    I used export to set the env variables. But the problem is its session specific. If I open new session the values set will be gone. Thank you in advance