DEV Community

BC
BC

Posted on

List all current environment variables - Linux Tips

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
...
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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

$ ./listenv
SHELL=/bin/bash
SESSION_MANAGER=local/pop-os
COLORTERM=truecolor
...
Enter fullscreen mode Exit fullscreen mode

Top comments (0)