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; ./program
my=4 ./program
env my=4 ./program
Each 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.