2

I need to save environment variables to a file and (later) a process should import them. I need this to workaround a program fooprog that nullifies the environment before executing a barscript, and I need some environment variables in barscript. So I'm planning on saving all environment variables to a file before executing fooprogram, and make barscript source them from a file.

I tried this, but it doesn't work if there are variables that contain spaces.

$ env > my_environment
$ . my_environment

I guess the correct way is to fiddle with /proc/$$/environ and parsing this from barscript somehow, but I can't find the correct way of doing that.

edit: Quotes or newlines are problematic too. How could it be done so that envars as problematic as the following could be sourced without problems?

PROBLEMATIC='this has double quotes " and single quotes '\'' and even
newlines.

See?'
5
$ declare -p > my_environment

Later, inside barscript:

. my_environment

declare -p outputs environment variables in a form that can be executed by the shell, including quoting and escaping of variables as required.

$ foobar='"some double-quoted text"'
$ echo $foobar 
"some double-quoted text"
$ declare -p foobar
declare -- foobar="\"some double-quoted text\""

BTW, if you don't want to output your entire environment, you don't have to. Just name the vars you want to output on the declare -p command line:

$ declare -p HOME PATH foobar
declare -x HOME="/home/cas"
declare -x PATH="/usr/local/sbin:/usr/sbin:/sbin:/usr/local/bin:/usr/bin:/bin:/usr/bin/X11"
declare -- foobar="\"double-quoted-text\""

or pipe through grep -v to exclude specific vars you don't want in the output.

To get only the exported variables:

declare -p -x > my_environment

For more info, see help declare in bash.

  • This is almost what I want. I've been looking at help declare and trying things, but I cannot find a way to only print the exported envars. – Carlos Campderrós May 20 '16 at 9:41
  • the grep -- -x trick fails with multiline variables. I'm working on a way to get only the exported variable names to declare -p $(...) (cannot use xargs as declare is a builtin). I got declare -p $(env -0 | grep -zo '^\w\+=' | sed -e 's/=$//') which seems to work, although it seems little maintenance nightmare. – Carlos Campderrós May 20 '16 at 9:55
  • yep, see updated answer. declare -p -x, no need for grep. – cas May 20 '16 at 9:55
  • anyway @cas your help is greatly appreciated :) – Carlos Campderrós May 20 '16 at 9:56
  • 1
    I dunno. "drugs" is the excuse I use :) – cas May 20 '16 at 10:04

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.