I'm currently working on a program, and I would like to print special output if an environment variable is set.
For example, suppose I want environment variable "DEBUG"
.
In my bash command prompt, I set DEBUG
by typing the command: DEBUG=
Then in my C program, I can verify this environment variable is set by printing out all the content of char **environ
. DEBUG
does show up in this environment printout.
However, I don't know how to retrieve this environment variable for conditional checking. I've tried using the function getenv like so:
getenv("DEBUG")
If I were to try to print out this output like below I get a seg fault:
printf("get env: %s\n", getenv("DEBUG"));
I even tried this on a known environment variable like "HOME"
:
printf("get env: %s\n", getenv("HOME"));
which still produces a seg fault.
Does any one have any experience checking if an environment variable is set from a C program? I'm having issues even pulling a single environment variable which is preventing me from doing so.
getenv
returns NULL
when the environment variable for which it is asked is not set. Your check could thus simply be
if(getenv("DEBUG")) {
// DEBUG is set
} else {
// DEBUG is not set
}
Note that there is a difference between shell and environment variables; if you want a variable to show up in the environment of a shell's subprocess, you have to export
it in the shell:
export DEBUG=some_value
or
DEBUG=some_value
export DEBUG
It is not enough to just say DEBUG=some_value
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments