How to set environment variable in Linux permanently

Viewed 23647

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

6 Answers

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!@#

This is working inside Debian 11. It should work on other Debian based distributions like Ubuntu etc. I am using the old school nano to edit the file named pam_env.conf that resides in /etc/security/ directory, you may use whatever else you want instead of nano.

sudo nano /etc/security/pam_env.conf

Format for setting the environment variable inside this file is following:

VARIABLE [DEFAULT=[value]] [OVERRIDE=[value]]

(For example, let's set DXVK_HUD variable with the value full. This is equivalent to export DXVK_HUD=full You can replace the variable name and it's value to whatever you want for your use cases.)

This is how it is going to look inside that file as a new line:

DXVK_HUD DEFAULT=full OVERRIDE=full

Make the changes by saving it ( CTRL+O key combination is used for making changes through nano). Then press return (Enter key). And then press CTRL+X to exit from nano.

Restart your system. And type env in Terminal and see if you can see your environment variable in the list. It should be there.

Related