3

google is giving no love on this one today, so I turn to the experts...

I'm currently hacking together a script that relies on the /proc/pid/environ feature in Linux (RHEL 4) to check for a particular environment variable. Trouble is, it seems certain environment variables aren't showing up in there for some reason.

Example:

create some test vars:
$ export T_1=testval TEST_1=testval T=testval TESTING_LONGEST=testval

open a subshell:
$bash

$ cat /proc/self/environ|tr "\0" "\n"|grep testval
TESTVARIABLE_LONGEST=testval
T=testval

hmm... where did T_1 and TEST_1 go?? what rules govern this strange universe?

Thanks in advance, Josh

UPDATE:

I have been able to reproduce this issue on various RHEL versions and with various users, but it seems it is unique to Bash (I'm using 3.0). ksh does not show this behavior.

Josh Arenberg
  • 133
  • 1
  • 5
  • 1
    It seems to work fine on my system. Before you launch your sub-shell run the command `export | grep testval` and make sure everything really exists. – Zoredache Apr 16 '10 at 16:32
  • They are there. Perhaps we're looking at an issue with a particular RHEL release. – Josh Arenberg Apr 16 '10 at 16:44
  • Try a different approach and see if it gives you the same results: `grep -z testval /proc/self/environ | xargs -I{} -0 printf \{\}"\n"` or `set | grep testval` – Dennis Williamson Apr 16 '10 at 17:41
  • Dennis, your first test produces the same result, but the second test shows them, as does 'env|grep testval'. So they are making it into the shell, but not into /proc/pid/environ. – Josh Arenberg Apr 16 '10 at 17:47
  • Works as expected on my system(s). Bash 3.2, 2.6.24 kernel, Ubuntu 8.04. – Insyte Apr 16 '10 at 19:02
  • Out of curiosity, why are you looking in `/proc/*/environ` for your variables? Isn't easier just to check if it's set? `[[ -z "$TEST_1" ]]` – Insyte Apr 16 '10 at 19:04

3 Answers3

1

Have a look at Environment variables of a running process on Unix? ; it notes that /proc/*/environ is limited to 4096 bytes on some kernels, and that it doesn't display env vars that were changed in that shell.

0

Try using strings instead of tr. It's much better at finding readable strings than just replacing NULs with newlines.

strings /proc/$$/environ
ptman
  • 27,124
  • 2
  • 26
  • 45
  • 2
    That is not a good idea. The format of the `environ` pseudo-file is easy to understand, and replacing all NUL characters with newlines is the way to turn it into readable text. – kasperd Dec 27 '15 at 12:00
0

Some files in /proc don't respond well to being read in small blocks. Try something like this instead:

dd if=/proc/self/environ bs=1024k | tr "\0" "\n" | grep testval
apenwarr
  • 2,012
  • 1
  • 11
  • 11