简体   繁体   中英

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?

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

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"

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 :)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM