Skip to content
systemcoding.dev
Systems Programming

Print All Environment Variables Using environ

The global environ is the NULL-terminated array behind getenv. Loop over it to list every NAME=value entry, split entries safely and avoid the stale envp trap.

7 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the C, Linux and FreeBSD logos.

getenv() answers one question: what is the value of this variable? Sometimes you need the other one: what variables are there at all? A debugging tool that dumps its environment, a launcher that copies a filtered subset to a child, a wrapper that prints what a service actually received: all of these need the whole list. The environment is stored in a global array of strings called environ, and walking it is a five-line loop. This post shows that loop, splits each entry into name and value, sorts and filters the list, demonstrates why the third parameter of main() goes stale after setenv() while environ does not, and covers the declaration you need. It uses C17, GCC 14 and glibc 2.40 on Linux 6.12 and follows environ(7) and POSIX.1-2024. The surrounding mechanics are in the complete guide to program startup.

The array

The process environment is an array of pointers to strings of the form NAME=value, ending with a null pointer, and the global variable environ points to its first element:

c
extern char **environ;

POSIX requires you to declare it yourself in your program, because no standard header is obliged to. With glibc, <unistd.h> declares it when _GNU_SOURCE is defined before the first include; declaring it yourself works everywhere and costs one line. The array is null-terminated, so a loop needs no count.

Listing everything

list_env.cc
#include <stdio.h>

extern char **environ;

int main(void)
{
    for (char **entry = environ; *entry != NULL; entry++)
        printf("%s\n", *entry);
    return 0;
}
Shell
env -i LANG=C.UTF-8 TZ=UTC EDITOR=vi ./list_env
Text
LANG=C.UTF-8
TZ=UTC
EDITOR=vi

The order is the order in which the caller built the array, which for a shell is not alphabetical and not stable between systems. Do not rely on it, and sort when you need a predictable output. The array can also be empty: environ is then not null but points to an array whose first element is NULL; with some implementations, after clearenv(), environ itself may be NULL, so guard against it if your program can run after a clear.

Splitting an entry into name and value

Each entry has one meaningful equals sign: the first one. Everything before it is the name, and everything after it, including any further equals signs, is the value. strchr() finds the first:

split_env.cc
#include <stdio.h>
#include <string.h>

extern char **environ;

int main(void)
{
    for (char **entry = environ; *entry; entry++) {
        const char *eq = strchr(*entry, '=');
        if (eq == NULL) {
            printf("malformed entry (no '='): %s\n", *entry);
            continue;
        }
        int name_len = (int)(eq - *entry);
        printf("name=%.*s  value=%s\n", name_len, *entry, eq + 1);
    }
    return 0;
}
Shell
env -i OPTS=a=b,c=d EMPTY= ./split_env
Text
name=OPTS  value=a=b,c=d
name=EMPTY  value=

The %.*s format prints exactly name_len characters from the entry, so no copy is needed. The malformed branch is not decoration: an entry with no equals sign can legally appear in an environment built by a careless program, and a loop that assumes strchr() succeeds crashes on it.

Sorting and filtering

A debug dump is easier to read sorted, and a launcher usually wants only a subset. Both are short with qsort() over the pointer array. This version prints the entries whose names start with a given prefix, in alphabetical order:

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

extern char **environ;

static int by_text(const void *a, const void *b)
{
    return strcmp(*(char *const *)a, *(char *const *)b);
}

int main(int argc, char *argv[])
{
    const char *prefix = argc > 1 ? argv[1] : "";
    size_t plen = strlen(prefix);

    size_t count = 0;
    while (environ[count])
        count++;

    char **matches = malloc((count + 1) * sizeof *matches);
    size_t n = 0;
    for (size_t i = 0; i < count; i++)
        if (strncmp(environ[i], prefix, plen) == 0)
            matches[n++] = environ[i];

    qsort(matches, n, sizeof *matches, by_text);
    for (size_t i = 0; i < n; i++)
        puts(matches[i]);

    free(matches);
    return 0;
}
Shell
env -i APP_PORT=8080 APP_DEBUG=1 HOME=/root APP_NAME=demo ./env_prefix APP_
Text
APP_DEBUG=1
APP_NAME=demo
APP_PORT=8080

The array holds pointers into the environment, so matches holds pointers to the originals; sorting rearranges the copy of the pointer array only and leaves environ untouched. Never sort environ itself, since other code reads it concurrently with your assumptions about its order.

Why environ and not the third parameter of main

Many Unix programs receive the environment as the third argument of main():

c
int main(int argc, char *argv[], char *envp[]);

That works for reading at startup, but envp is a plain copy of the pointer made when the program started. When setenv() adds a variable and needs more room, the C library allocates a bigger array, copies the pointers and updates environ to point at the new one. envp still points at the original array, which does not contain the new variable. The program below shows the difference:

stale_envp.cc
#include <stdio.h>
#include <stdlib.h>

extern char **environ;

static int count(char **env)
{
    int n = 0;
    while (env[n])
        n++;
    return n;
}

int main(int argc, char *argv[], char *envp[])
{
    (void)argc;
    (void)argv;

    printf("before: envp=%d environ=%d\n", count(envp), count(environ));

    setenv("A_NEW_VARIABLE", "1", 1);
    setenv("ANOTHER_ONE", "2", 1);

    printf("after : envp=%d environ=%d\n", count(envp), count(environ));
    return 0;
}
Shell
env -i HOME=/root ./stale_envp
Text
before: envp=1 environ=1
after : envp=1 environ=3

Before any change both pointers see the single HOME entry. After two setenv() calls, environ reports three entries while envp still reports one: the original array lives on the stack and cannot grow, so the library built a new, larger array in the heap and pointed environ at it, leaving envp looking at the old one. Code that reads envp after a change sees a world that no longer exists, and code that reads environ sees the current one. That is why anything that lists or copies the environment should use environ.

Building an environment for a child

The list is also the starting point for a filtered copy to pass to a child. A launcher that wants to keep PATH and LANG and drop everything else collects the matching entries into a new array and passes it to execve():

filtered_env.cc
#include <stdlib.h>
#include <string.h>

extern char **environ;

/* Returns a NULL-terminated array of pointers to the kept entries. Free with free(). */
char **filtered_environment(const char *const keep[])
{
    size_t total = 0;
    while (environ[total])
        total++;

    char **out = malloc((total + 1) * sizeof *out);
    if (!out)
        return NULL;

    size_t n = 0;
    for (char **e = environ; *e; e++) {
        for (size_t k = 0; keep[k]; k++) {
            size_t len = strlen(keep[k]);
            if (strncmp(*e, keep[k], len) == 0 && (*e)[len] == '=') {
                out[n++] = *e;              /* points at the original string */
                break;
            }
        }
    }
    out[n] = NULL;
    return out;
}

The check (*e)[len] == '=' prevents PATH from also matching PATHEXT. The returned pointers refer to the strings that environ already owns, so the array is valid for as long as the environment is unchanged, and passing it to execve() immediately is the safe use. The dedicated post on custom child environments finishes this thought with execve() and posix_spawn().

Do not do these

  • Do not modify the strings in environ in place. A longer value overruns into the next entry.

  • Do not assume order, uniqueness or that every entry has an equals sign.

  • Do not walk environ while another thread calls setenv() or unsetenv(); the array can be reallocated under you.

  • Do not print the whole environment into logs on a production system, because it commonly contains tokens and passwords.

Common uses of the full list

Four tasks genuinely need the whole environment, not a single lookup. A diagnostic command that prints what a service received, which is how you debug the difference between your shell and a systemd unit. A launcher that forwards a filtered subset to a child, as shown above. A wrapper that records the environment for reproducibility, writing the sorted list to a file next to a build artifact. And a sandbox that wants to drop everything except an allow-list.

For the first, redact values you should not print. Variable names that contain TOKEN, SECRET, PASSWORD or KEY are good candidates, and the safe approach is to print the name and a placeholder:

c
static int looks_secret(const char *name, size_t len)
{
    static const char *marks[] = { "TOKEN", "SECRET", "PASSWORD", "KEY", NULL };
    for (int i = 0; marks[i]; i++) {
        size_t m = strlen(marks[i]);
        for (size_t p = 0; p + m <= len; p++)
            if (strncmp(name + p, marks[i], m) == 0)
                return 1;
    }
    return 0;
}

Call it with the name and its length and print NAME=<redacted> when it returns 1. Heuristics like this miss some secrets, so a debug dump should still never go to a shared log without a human check.

A note on duplicated names

Nothing stops the array from holding the same name twice, and a program that builds an environment by appending can produce that. getenv() returns the first match, while some child programs and shells take the last, so the two disagree about the value. If you merge variables from several sources, deduplicate before building the array: scan for the name before appending, and replace the existing entry instead of adding a second one. Use setenv() with overwrite for the same reason, since it never creates a duplicate.

Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.