5

I have tried to extract environment variables in a Python process with help of env --null, which works even for environment variables containing newline character.

But on some machines I have received an error:

> env -0
env: invalid option -- '0'

> env --null
env: unrecognized option '--null'

> env --version
env (GNU coreutils) 6.12
Copyright (C) 2008 Free Software Foundation, Inc.

In which version was the argument introduced? Is there any alternative command to extract the environment?

6

Option -0/--null was first introduce on 28-10-2009, and release with GNU coreutils version 8.1.

If your coreutils is too old, you should upgrade. Or you can use perl:

perl -e '$ENV{_}="/usr/bin/env"; print "$_ => $ENV{$_}\0" for keys %ENV'

As @Stéphane Chazelas pointed out in his comment, the above approach doesn't include environment strings that don't contain =, duplicated environment variables or environment variables with null name.

If you are in Linux, you can use (Thanks @Stéphane Chazelas again):

cat /proc/self/environ
  • Note that it doesn't include the environment strings that don't contain = or duplicated env vars or env vars with the null name (=value env strings). – Stéphane Chazelas Jan 13 '15 at 17:03
  • @StéphaneChazelas: Can you give example for each of them? I even don't know how can we create env vars with null name. – cuonglm Jan 13 '15 at 17:12
  • tcc -run - <<< 'int main() { char*e[] = { "a=b", "a=c", "", "=", 0}; execle("/usr/bin/env", "env", "-0", 0, e); }' – Stéphane Chazelas Jan 13 '15 at 17:19
  • @StéphaneChazelas: Thanks for that information, updated my answer. – cuonglm Jan 13 '15 at 17:34
3

If you are working with python anyway you could use:

import os
import sys

for k in sorted(os.environ):
    if k == '_':
        v = '/usr/bin/env'
    else:
        v = os.environ[k]
    sys.stdout.write("{}={}\0".format(k, v))

to get very similar output compared to env --null.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.