Question

I have a C program that prints every environmental variable, whose name is given by stdin. It prints variables such as $PATH, $USER but it doesn't see the environmental variables i define myself in the Linux shell... For instance, in bash I define my=4, and I expect the program to return 4 when I give the input "my".

int main  () {
  char * key = (char * )malloc(30);

  scanf("%s", key);

  if(getenv(key) != NULL)
    printf("%s\n", getenv(key));
  else
    printf("NULL\n");

  return 0;
}

What can I do in order to improve the results of getenv? I want it to show me all the environmental variables with all the inheritances from the Linux shell . Thank you..

Was it helpful?

Solution

There are a couple of ways:

  1. my=4; export my; ./program
  2. my=4 ./program
  3. env my=4 ./program

Each of these methods has the same effect, but through different mechanisms.

  1. This method is specific to the shell that you're using, although it works like this in most typical shells (Bourne shell variants; csh-derived shells are different again). This first sets a shell variable, then exports it to an environment variable, then runs your program. On some shells, you can abbreviate this as export my=4. The variable remains set after your program runs.

  2. This method is also dependent on your shell. This sets the my environment variable temporarily for this execution of ./program. After running, my does not exist (or has its original value).

  3. This uses the env program to set the environment variable before running your program. This method is not dependent on any particular shell, and is the most portable. Like method 2, this sets the environment variable temporarily. In fact, the shell never even knew that my was set.

OTHER TIPS

If you didn't export it then it's just a shell variable, not an environment variable. Use export my=4 or my=4; export my.

This has nothing to do with C or getenv. If you do my=4 in the shell, you have defined a local shell variable. To make that an environment variable, do export my.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top