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 $PID
.
We can read the initial variables from the /proc/$PID/environ
file:
cat /proc/$PID/environ
Example output:
b=2a=1SHELL=/bin/bashWINDOWID=16831489QT_ACCESSIBILITY=1COLORTERM=rxvt-xpm ...
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.
Alternatives
Alternatively, we could also use ps
for this purpose:
ps e -p $PID -ww
We're using 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 ...
Updated values
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"
Note: This is a snapshot of the wiki page from the BetterWays.dev wiki, you can find the latest, fully formatted version here: betterways.dev/finding-out-environment-variables-of-the-process-on-linux.
Top comments (0)