How to permanently export a variable in Linux? How to permanently export a variable in Linux? linux linux

How to permanently export a variable in Linux?


You can add it to your shell configuration file, e.g. $HOME/.bashrc or more globally in /etc/environment.After adding these lines the changes won't reflect instantly in GUI based system's you have to exit the terminal or create a new one and in server logout the session and login to reflect these changes.


You have to edit three files to set a permanent environment variable as follow:

  • ~/.bashrc

    When you open any terminal window this file will be run. Therefore, if you wish to have a permanent environment variable in all of your terminal windows you have to add the following line at the end of this file:

    export DISPLAY=0
  • ~/.profile

    Same as bashrc you have to put the mentioned command line at the end of this file to have your environment variable in every login of your OS.

  • /etc/environment

    If you want your environment variable in every window or application (not just terminal window) you have to edit this file. Add the following command at the end of this file:

    DISPLAY=0

    Note that in this file you do not have to write export command

Normally you have to restart your computer to apply these changes. But you can apply changes in bashrc and profile by these commands:

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

But for /etc/environment you have no choice but restarting (as far as I know)

A Simple Solution

I've written a simple script for these procedures to do all those work. You just have to set the name and value of your environment variable.

#!/bin/bashecho "Enter variable name: "read variable_nameecho "Enter variable value: "read variable_valueecho "adding " $variable_name " to environment variables: " $variable_valueecho "export "$variable_name"="$variable_value>>~/.bashrcecho $variable_name"="$variable_value>>~/.profileecho $variable_name"="$variable_value>>/etc/environmentsource ~/.bashrcsource ~/.profileecho "do you want to restart your computer to apply changes in /etc/environment file? yes(y)no(n)"read restartcase $restart in    y) sudo shutdown -r 0;;    n) echo "don't forget to restart your computer manually";;esacexit

Save these lines in a shfile then make it executable and just run it!


add the line to your .bashrc or .profile. The variables set in $HOME/.profile are active for the current user, the ones in /etc/profile are global. The .bashrc is pulled on each bash session start.