Environment Variables

Enivronmental variables are often used to control the behavior of shell scripts and other programs. You can also use them to configure the user's environment. For example, each user has an environment variable HOME, that defines his home directory, the default starting place for his or her session. The HOME variable is one of many standard environment variables. We can examine environment variables from the shell prompt:


$echo $HOME
/home/john

A C program may gain access to environment variables using the getenv and putenv functions.


#include <stdlib.h>

char *getenv(const char *name);
int putenv(const char *string);

The environ variable

The program environment is made up of strings of the form name=value. This array of strings is made available to programs directly via the environ variable, which is declared as


#include <stdlib.h>

extern char **environ;

In Unix systems you can define main a third way, using three arguments:

int main (int argc, char *argv[], char *envp[])

The first two arguments are just the same. The third argument envp gives the program's environment; it is the same as the value of environ. The three-argument form is not as portable, so it is best to write main to take two arguments, and use the value of environ.

References

Neil Matthew and Richard Stone, Beginning Linux Programming, Third Edition,
Wrox, 2004. ISBN 0-7645-4497-7. p 142-146.

Environment Variables (from the GNU C Library Reference Manual).


Maintained by John Loomis, last updated 4 September 2006