I have a C program that prints every environment variable whose name is given by stdin.
It prints variables such as $PATH, $USER but it doesn't see the environment 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 environment variables with all the inheritances from the Linux shell.
Thank you.
There are a couple of ways:
my=4; export my; ./programmy=4 ./programenv my=4 ./programEach of these methods has the same effect, but through different mechanisms.
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.
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With