Print Environment Variables

Print environment variables – C Program

Ankur Kulhari

In this article, we will discuss about a C program to print environment variables. Environment variables are a set of dynamic named values that can affect the way running processes will behave on a computer.

In the main function,

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

The third argument envp gives the program’s environment. env is available as an argument to main function, as envp – an array of strings which stores all the environment variables and is terminated by a null. We can use it to get all the environment variables from C, C++, gcc, linux or unix environment. We have also attached a link at the end of the article which takes you to an online compiler where you can execute this code to see the output yourself.

Following is the program to print environment variables:
env_var.c

#include <stdio.h>
int main(int argc, char **argv, char** envp)
{
  int i;
  char *s = *envp;
  //Loop starts from i=1 (as the 1st argument stores the filename itself)
  for (i = 1; s; i++)
  {
    //and goes until s becomes NULL (as the envp array is terminated by NULL)
    printf("%s\n", s);

    // To increment the index of s pointer
    s = *(envp + i);
  }
  return 0;
}

Executing it:
Open terminal (ctrl+x) –> change pwd to the location where your env_var.c is placed.
type: “gcc env_var.c” to compile it
type: “./a.out” to execute it

OUTPUT

HOSTNAME=localhost.localdomain
SELINUX_ROLE_REQUESTED=
SHELL=/bin/bash
TERM=xterm
HISTSIZE=1000
SSH_CLIENT=192.168.7.43 49162 22
SELINUX_USE_CURRENT_RANGE=
QTDIR=/usr/lib64/qt-3.3
QTINC=/usr/lib64/qt-3.3/include
SSH_TTY=/dev/pts/8
USER=harika
LS_COLORS=rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:........
PATH=/usr/lib64/qt-3.3/bin:/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/harika/bin:.
MAIL=/var/spool/mail/harika
PWD=/home/harika
KDE_IS_PRELINKED=1
LANG=en_US.UTF-8
KDEDIRS=/usr
SELINUX_LEVEL_REQUESTED=
HISTCONTROL=ignoredups
SSH_ASKPASS=/usr/libexec/openssh/gnome-ssh-askpass
HOME=/home/harika
SHLVL=2
LOGNAME=harika
CVS_RSH=ssh
QTLIB=/usr/lib64/qt-3.3/lib
SSH_CONNECTION=192.168.7.43 49162 192.168.7.140 22
LESSOPEN=|/usr/bin/lesspipe.sh %s
G_BROKEN_FILENAMES=1
_=./a.out
OLDPWD=/home

You can try it online at https://ideone.com/OdDYc3

If you find any issues in the code, please comment below and we will fix it. Do you know a better method to do this task or in a different language? Comment below and we will also add your solution to help other.

References : GNU

What do you think about the article?