views:

108

answers:

4

I have this following simple program:

int main()
{
    char* v = getenv("TEST_VAR");
    cout << "v = " << (v==NULL ? "NULL" : v) << endl;
    return 0;
}

These lines are added to .bashrc file:

TEST_VAR="2"
export TEST_VAR

Now, when I run this program from the terminal window (Ubuntu 10.04), it prints v = 2. If I run the program by another way: using launcher or from Eclipse, it prints NULL. I think this is because TEST_VAR is defined only inside bash shell. How can I create persistent Linux environment variable, which is accessible in any case?

+2  A: 

Add that to .bash_profile (found in your home directory). You will need to log out and log back in for it to take effect.

Also, since you are using bash, you can combine the export and set in a single statement:

export TEST_VAR="2"
R Samuel Klatchko
.bash_profile doesn't exist on my computer. I created new file and moved TEST_VAR to it. After reboot, TEST_VAR is not available even in the shell.
Alex Farber
+2  A: 

On my system (Fedora 13) you can make system wide environment variables by adding them under /etc/profile.d/.

So for example if you add this to a file in /etc/profile.d/my_system_wide.sh

SYSTEM_WIDE="system wide"
export SYSTEM_WIDE

and then open a another terminal it should source it regardless of who the user is opening the terminal

echo $SYSTEM_WIDE
system_wide
sashang
Thanks, this did the trick.
Alex Farber
A: 

There is no such thing as a system-wide environment variable on Linux. Every process has its own environment. Now by default, every process inherits its environment from its parent, so you can get something like a system-wide environment by ensuring that a var is set in an ancestor of every process of interest. Then, as long as no other process changes that var, every process of interest will have it set.

The other answers here give various methods of setting variables early. For example, .bash_profile sets it in every login process a user runs, which is the ultimate parent of every process they run after login. /etc/profile is read by every bash login by every user.

Chris Dodd
A: 

Sorry if I'm being naive but isn't .bash_profile useful only if you are running bash as your default shell ?

I 'sometimes' use Linux and mostly use ksh. I have .profile so may be you should check for .*profile and export the variable there.

Good luck :)

DeltaRogue