Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set environment variable in Linux permanently

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

like image 454
Sylvia Lobo Avatar asked Dec 19 '22 05:12

Sylvia Lobo


2 Answers

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
like image 58
marcdahan Avatar answered Jan 06 '23 14:01

marcdahan


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!@#
like image 37
avivamg Avatar answered Jan 06 '23 13:01

avivamg