Ubuntu – How to add environment variables

bash

I'm running Ubuntu 11.04. I use the terminal to start a bash session, and I want to add an environment variable:

$r@hajt:~$ env THEVAR=/example

But it's not working. It shows all the variables with THEVAR being the last one, but another call to env does not show THEVAR anymore- env | grep THEVAR returns nothing.

Similarly, scripts with export (export THEVAR=/example) or other variable assignments (THEVAR=/example) don't add the environment variable.

I know I'm doing something wrong, I know it should be something simple, but I just can't find what.

UPDATE:
The real meaning of my question was this one: https://stackoverflow.com/questions/496702/can-a-shell-script-set-environment-variables-of-the-calling-shell

(Anyway I'll choose the most voted answer and leave the edited title -that wasn't what I was asking)

env runs a program in a modified environment, then dismisses all the changes.

Best Answer

To set variable only for current shell:

VARNAME="my value"

To set it for current shell and all processes started from current shell:

export VARNAME="my value"      # shorter, less portable version

To set it permanently for all future bash sessions add such line to your .bashrc file in your $HOME directory.

To set it permanently, and system wide (all users, all processes) add set variable in /etc/environment:

sudo -H gedit /etc/environment

This file only accepts variable assignments like:

VARNAME="my value"

Do not use the export keyword here.

You need to logout from current user and login again so environment variables changes take place.

Related Question