loading...

List all current environment variables - Linux Tips

0xbf profile image Bo ・1 min read

Here we introduce 2 ways to list out all current environment variables:

1, use printenv command:

$ printenv
SHELL=/bin/bash
SESSION_MANAGER=local/pop-os
COLORTERM=truecolor
...

2, write a C program to list them

Environment variables will be put in a environment table in process, and it has a pre-defined environ pointer points to that table. To iterate all environment variables, we just need to walk through this table via the pointer:

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

extern char** environ;

int main() {
    char** ep = NULL;
    for (ep=environ; *ep!=NULL; ep++) {
        puts(*ep);
    }
    return 0;
}

Compile and run it: gcc main.c -o listenv

$ ./listenv
SHELL=/bin/bash
SESSION_MANAGER=local/pop-os
COLORTERM=truecolor
...

Discussion

markdown guide