Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using getenv function in Linux

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?

like image 898
Alex F Avatar asked Sep 02 '25 02:09

Alex F


2 Answers

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
like image 62
sashang Avatar answered Sep 04 '25 16:09

sashang


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"
like image 21
R Samuel Klatchko Avatar answered Sep 04 '25 14:09

R Samuel Klatchko