Coder Perfect

In Linux, how do I export a variable indefinitely?

Problem

I’m running RHEL6, and I’ve exported the following environment variable:

export DISPLAY=:0

When the terminal is closed, that variable is gone. How can I make this a permanent addition so that this variable value is always associated with a specific user?

Asked by user1340582

Solution #1

You can include it in your shell configuration file, such as $HOME/.bashrc, or in /etc/environment more broadly. On GUI-based systems, the changes won’t show up right away; you’ll need to close the terminal or establish a new one, and in servers, you’ll need to log out and back in to see the changes.

Answered by Antoine

Solution #2

To set a permanent environment variable, you must change three files as follows:

In most cases, you’ll need to restart your computer to see these changes take effect. These commands, however, can be used to make changes to bashrc and profile:

$ source ~/.bashrc
$ source ~/.profile

However, you have no choice except to restart /etc/environment (as far as I know)

To complete all of these tasks, I’ve built a simple script. All you have to do now is give your environment variable a name and a value.

#!/bin/bash
echo "Enter variable name: "
read variable_name
echo "Enter variable value: "
read variable_value
echo "adding " $variable_name " to environment variables: " $variable_value
echo "export "$variable_name"="$variable_value>>~/.bashrc
echo $variable_name"="$variable_value>>~/.profile
echo $variable_name"="$variable_value>>/etc/environment
source ~/.bashrc
source ~/.profile
echo "do you want to restart your computer to apply changes in /etc/environment file? yes(y)no(n)"
read restart
case $restart in
    y) sudo shutdown -r 0;;
    n) echo "don't forget to restart your computer manually";;
esac
exit

Simply save these lines in a shfile, make it executable, then execute it!

Answered by e3oroush

Solution #3

Add the line to your.profile or.bashrc file. The settings in $HOME/.profile are only active for the current user; the variables in /etc/profile are global. Each time a bash session starts, the.bashrc file is loaded.

Answered by kostja

Solution #4

Use the following places on Ubuntu systems:

Check out this Ask Ubuntu response for more information on #2. NOTE: #3 is Ubuntu’s advice, although it could pose a security risk in the real world.

Answered by csi

Solution #5

If anyone is interested, here are some quick recommendations for permanently adding environment variables.

vi ~/.bash_profile

Fill in the following variables in the file:

export DISPLAY=:0
export JAVA_HOME=~/opt/openjdk11

Apply all changes right away:

source ~/.bash_profile

Source: https://www.serverlab.ca/tutorials/linux/administration-linux/how-to-set-environment-variables-in-linux/

Answered by dasilvadaniel

Post is based on https://stackoverflow.com/questions/13046624/how-to-permanently-export-a-variable-in-linux