2

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

Pierre Ozoux
  • 780
  • 7
  • 25
  • are you sure you need to do that? Processes started from a process inherit the invoking process' environment. – Marcus Müller Apr 01 '15 at 12:20
  • Take a look at the link github issue to understand why this question is being asked. The end goal is to start a shell inside a Docker container that has the same environment variables available as PID 1 in the container. – larsks Apr 01 '15 at 13:45

2 Answers2

2

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.

larsks
  • 277,717
  • 41
  • 399
  • 399
  • Thank you very much for your time on this, but it's a bit sad to add such a big dependency (python) to do something that looks like easy. I think I'll use sed or awk to do the same. – Pierre Ozoux Apr 01 '15 at 14:30
  • 1
    So, write it in C or go and compile it. I bet that both sed and awk will be problematic, too, especially when it comes to dealing with variable contents that contain quotes and such. – larsks Apr 01 '15 at 15:46
0

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
Tombart
  • 30,520
  • 16
  • 123
  • 136