How to show all the environment variables

This is a small guide on how to show all the environment variables. These command will came very handy in environments where, we are retrieving values from the environment. This is very common when working with containers or pods and will be very helpful if you are trying to debug.

From the shell you can run

~$ printenv

and you will see as output something like this

SHELL=/bin/bash
PWD=/home/d3
LOGNAME=d3
XDG_SESSION_TYPE=tty
MOTD_SHOWN=pam
HOME=/home/d3
LANG=en_US.UTF-8
LC_TERMINAL=iTerm2
LESSCLOSE=/usr/bin/lesspipe %s %s
XDG_SESSION_CLASS=user
TERM=xterm-256color
LESSOPEN=| /usr/bin/lesspipe %s
USER=d3
LC_TERMINAL_VERSION=3.4.8
SHLVL=1
XDG_SESSION_ID=4720
XDG_RUNTIME_DIR=/run/user/1000
XDG_DATA_DIRS=/usr/local/share:/usr/share:/var/lib/snapd/desktop
PATH=/home/d3/.local/bin:/snap/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus
SSH_TTY=/dev/pts/3
_=/usr/bin/printenv

This as it is, is not really useful but you can access these values programmatically. As example let’s set an environment variable and try to retrieve using python or php

~$ export TEST_VAL="abc"
~$ echo $TEST_VAL
abc

Now we have our TEST_VAL set

python example:

import os

val = os.getenv("TEST_VAL", "Not set")
print(val)

we can then execute

~$ python3 i.py
abc
~$ unset TEST_VAL
~$ python3 i.py
Not set

PHP example

<?php
$i = getenv("TEST_VAL") != "" ? getenv("TEST_VAL"): "Not set";
echo $i . PHP_EOL;
?>

we can then execute

~$ export TEST_VAL="abc"
~$ php i.php
abc
~$ unset TEST_VAL
~$ php i.php
Not set

Hope this helped

d3

d3 is an experienced Software Engineer/Developer/Architect/Thinker with a demonstrated history of working in the information technology and services industry. Really passionate about technology, programming languages and problem solving. He doesn't like too much the self celebration and prefers to use that time doing something useful ...i.e. coding

You may also like...