Skip to content
Advertisement

Using sed to get an env var from /proc/*/environ weirdness with x00

I’m trying to grovel through some other processes environment to get a specific env var.

So I’ve been trying a sed command like:

sed -n "s/x00ENV_VAR_NAME=([^x00]*)x00/1/p" /proc/pid/environ

But I’m getting as output the full environ file. If I replace the 1 with just a static string, I get that string plus the entire environ file:

sed -n "s/x00ENV_VAR_NAME=([^x00]*)x00/BLAHBLAH/p" /proc/pid/environ

I should just be getting “BLAHBLAH” in the last example. This doesn’t happen if I get rid of the null chars and use some other test data set.

This lead me to try transforming the x00 to x01’s, which does seem to work:

cat /proc/pid/environ | tr '00' '01' | sed -n "s/x01ENV_VAR_NAME=([^x01]*)x01/1/p"

Am I missing something simple about sed here? Or should I just stick to this workaround?

Advertisement

Answer

You could process the list with gawk, setting the record separator to and the field separator to =:

gawk -v 'RS=' -F= '$1=="ENV_VAR_NAME" {print $2}' /proc/pid/environ

Or you could use read in a loop to read each NUL-delimited line. For instance:

while read -d $'' ENV; do declare "$ENV"; done < /proc/pid/environ

echo $ENV_VAR_NAME

(Do this in a sub-shell to avoid clobbering your own environment.)

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement