Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List environment variables with C in UNIX

Is there a way to enumerate environment variables and retrieve values using C?

like image 587
Stepan Avatar asked Aug 13 '10 03:08

Stepan


People also ask

How do I list environment variables in Unix?

To list all the environment variables, use the command " env " (or " printenv "). You could also use " set " to list all the variables, including all local variables.

How do I display environment variables in Linux?

The most used command to displays the environment variables is printenv . If the name of the variable is passed as an argument to the command, only the value of that variable is displayed. If no argument is specified, printenv prints a list of all environment variables, one variable per line.

What is an environment variable C?

The C/C++ environment variables define the characteristics of a specific environment. Environment variables are inherited from system definitions, but can be modified at an application level without affecting the environment of other applications or the system settings.

Where are environment variables stored in Unix?

The Global environment variables of your system are stored in /etc/environment . Any changes here will get reflected throughout the system and will affect all users of the system.


1 Answers

Take a look at the environ global variable.

extern char **environ;

It might be defined in unistd.h (take a look at the environ (5) man page above).

Here's a little code demo I wrote:

#include <stdio.h>
extern char **environ;

int main()
{
    for (char **env = environ; *env; ++env)
        printf("%s\n", *env);
}

Here's how to use it:

matt@stanley:~/Desktop$ make enumenv CFLAGS=-std=c99
cc -std=c99    enumenv.c   -o enumenv
matt@stanley:~/Desktop$ ./enumenv 
ORBIT_SOCKETDIR=/tmp/orbit-matt
SSH_AGENT_PID=1474
TERM=xterm
SHELL=/bin/bash
... (so forth)
like image 66
Matt Joiner Avatar answered Oct 19 '22 08:10

Matt Joiner