Environment variable with spaces in a string - How to use them from /proc/pid/environ

2.6k Views Asked by At

I set a variable with spaces in a string to a new bash:

VAR='my variable with spaces' /bin/bash

And now if I want to start a new bash with the same environment, I would do something like:

ENV=$(cat /proc/self/environ | xargs -0 | grep =)
env -i - $ENV /bin/bash

But the thing is, in /proc/self/environ, this variable is without quotes. So the last command throws a: env: variable: No such file or directory

How can I work around this limitation?

PS: this is a simplified version of the following issue: https://github.com/jpetazzo/nsenter/issues/62

2

There are 2 best solutions below

0
On

Just add -L1 to xargs (max non-blank input lines per command line):

xargs -0 -L1 -a /proc/self/environ

This will give you each variable on a separate line, which makes it easier to process. Or simply use

strings /proc/self/environ
2
On

I think the answer here is to not use a shell script to set things up. Using a higher-level language makes it much easier to parse /proc/<PID>/environ into something useful. Here's a short example:

#!/usr/bin/python

import os
import sys
import argparse


def parse_args():
    p = argparse.ArgumentParser()
    p.add_argument('pid')
    p.add_argument('command', nargs=argparse.REMAINDER)
    return p.parse_args()


def main():
    args = parse_args()

    env = {}
    with open('/proc/%s/environ' % args.pid) as fd:
        for envspec in fd.read().split('\000'):
            if not envspec:
                continue

            varname, varval = envspec.split('=', 1)
            env[varname] = varval

    print env
    os.execvpe(args.command[0], args.command, env)


if __name__ == '__main__':
    main()

Put this in a file called env-from, make it executable, and then you can run:

env-from <pid> bash

And you'll get a shell using the environment variables from the specified process.