To get environment variables of specific process we use the next command:
cat /proc/<pid>/environ | tr '\0' '\n'
Is there similar command to list all environment variables from all processes? And is there one more similar command to list all values of specific environment variable from all processes?
CodePudding user response:
To get a list of all process IDs, you can use this one-liner:
ps -ef | awk '{print $2}' | tail -n 2
What this does, in three steps:
ps -ef
List process info of all processes running on the system, in standard format. Prints with a header row.awk '{print $2}'
Print just the second section, splitting by whitespace. The format ofps -ef
shows lines asUID
,PID
,PPID
,C
,STIME
,TTY
,TIME
, and finallyCMD
. We only want the second one, so theawk
command only gets the second column.tail -n 2
Cuts out the first line and only outputs the second line onwards. As mentioned previously, theps -ef
command has a header row, so we need to cut that for a bare list of PIDs.
To list all the environment variables for all of these PIDs, we can use the environ
files as you mentioned. To do this, we'll use a for
loop with an evaluated command (between the backticks).
for pid in `ps -ef | awk '{print $2}' | tail -n 2`;
do cat /proc/${pid}/environ;
done;
or this handy one-liner:
for pid in `ps -ef | awk '{print $2}' | tail -n 2`; do cat /proc/${pid}/environ; done;
This for
loop goes through that list of PIDs, assigning the variable pid
to each iteration, and executes the cat
command on each file with the PID in the path.
For readability, we can use strings
or tr
, both shown below.
for pid in `ps -ef | awk '{print $2}' | tail -n 2`; do strings /proc/${pid}/environ | cat; done;
for pid in `ps -ef | awk '{print $2}' | tail -n 2`; do tr '\0' '\n' </proc/${pid}/environ | cat; done;
You could also use tools such as cut
, sed
, xargs
, or anything else that gets the job done.
For finding specific environment variables, you can pipe all of that into grep
instead of cat
, which will automatically print to the console:
for pid in `ps -ef | awk '{print $2}' | tail -n 2`; do strings /proc/${pid}/environ | grep "SHELL"; done;