Finding out environment variables of the process on Linux📄 BetterWays.dev wiki page | 🕑 Last updated: Oct 14, 2022
As you probably know, each process on Linux can define its own environment variables (which are by default inherited by child processes).
Let's create an example process and pass it two environment variables:
a=1 b=2 sleep 120 & PID=$!
First, we're creating a process that will sleep for 120 seconds, then we're saving its process id (PID) in a variable named
We can read the initial variables from the
Since entries are separated by the null byte character ('\0'), the output is not very readable, so let's try to fix that:
sed -z 's/$/\n/' /proc/$PID/environ
-z option tells
sed that new lines are separated by the null byte character, instead of the usual newline character - exactly what we need here.
That output is now more readable:
b=2 a=1 SHELL=/bin/bash WINDOWID=16831489 QT_ACCESSIBILITY=1 COLORTERM=rxvt-xpm ...
Note: use this only for display purposes, entries are separated by the null byte character for a good reason - it's the only character that can't be part of the value.
Alternatively, we could also use
ps for this purpose:
ps e -p $PID -ww
e option to tell
ps to show the environment variables after the command,
-p to specify the process id, and
-ww for wide output (unlimited width).
Example output (entries are separated by spaces):
657114 pts/47 S 0:00 sleep 120 b=2 a=1 SHELL=/bin/bash WINDOWID=16831489 QT_ACCESSIBILITY=1 COLORTERM=rxvt-xpm ...
As I mentioned earlier,
/proc/$PID/environ contains only initial variables. If the process changes its environment, and you want to read updated variables, you'll need to do something like this:
echo 'p (char *) getenv("a")' | gdb -q -p $PID
The value should be included in the output:
(gdb) $1 = 0x7ffeddf781d4 "1"