Environment Variables in C

Environment variables are a universal mechanism for conveying configuration information to Unix programs. Let’s look at how to set, get, and list environment variables.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    // To set a key/value pair, use setenv
    // To get a value for a key, use getenv
    // getenv will return NULL if the key isn't present in the environment
    setenv("FOO", "1", 1);
    printf("FOO: %s\n", getenv("FOO"));
    printf("BAR: %s\n", getenv("BAR") ? getenv("BAR") : "");

    // Use environ to list all key/value pairs in the environment
    // environ is an array of strings in the form KEY=value
    // The array is terminated with a NULL pointer
    printf("\n");
    for (char **env = environ; *env != NULL; env++) {
        char *pair = strdup(*env);
        char *key = strtok(pair, "=");
        printf("%s\n", key);
        free(pair);
    }

    return 0;
}

Running the program shows that we pick up the value for FOO that we set in the program, but that BAR is empty.

$ gcc environment-variables.c -o environment-variables
$ ./environment-variables
FOO: 1
BAR: 

The list of keys in the environment will depend on your particular machine.

TERM_PROGRAM
PATH
SHELL
...
FOO

If we set BAR in the environment first, the running program picks that value up.

$ BAR=2 ./environment-variables
FOO: 1
BAR: 2
...

Note that in C, we need to include the necessary header files and use the environ external variable to access the environment. The setenv and getenv functions are used to set and get environment variables, respectively. We use strdup and free to safely handle memory when splitting the environment strings.