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?

Peter Petrik
  • 153
  • 6

2 Answers2

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
cuonglm
  • 150,973
  • 38
  • 327
  • 406
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.

Anthon
  • 78,313
  • 42
  • 165
  • 222