10

The linux command line tool env can dump the current environment.

Since there are some special characters I want to use env -0 (end each output line with 0 byte rather than newline).

But how to load this dump again?

Bash Version: 4.2.53

guettli
  • 25,042
  • 81
  • 346
  • 663

2 Answers2

21

Don't use env; use declare -px, which outputs the values of exported variables in a form that can be re-executed.

$ declare -px > env.sh
$ source env.sh

This also gives you the possibility of saving non-exported variables as well, which env does not have access to: just use declare -p (dropping the -x option).


For example, if you wrote foo=$'hello\nworld', env produces the output

foo=hello
world

while declare -px produces the output

declare -x foo="hello
world"
chepner
  • 497,756
  • 71
  • 530
  • 681
4

If you want to load the export of env you can use what is described in Set environment variables from file:

env > env_file
set -o allexport
source env_file
set +o allexport

But if you happen to export with -0 it uses (from man env):

-0, --null
end each output line with 0 byte rather than newline

So you can loop through the file using 0 as the character delimiter to mark the end of the line (more description in What does IFS= do in this bash loop: cat file | while IFS= read -r line; do … done):

env -0 > env_file
while IFS= read -r -d $'\0' var
do
   export "$var"
done < env_file
Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • The first solution does not work in my case: `env > env_file` `set -o allexport` `source env_file` output `-bash: PROFILEREAD: readonly variable bash: 52052: command not found ... (a lot of command not found messages)` – guettli Aug 24 '16 at 09:21
  • 1
    The second solution (env -0) works, except: `PROFILEREAD readonly variable` – guettli Aug 24 '16 at 09:23
  • @guettli uhms, this is because that variable of yours is set to readonly. There are [some hacks on how to reset them](http://stackoverflow.com/a/17398009/1983854)... – fedorqui Aug 24 '16 at 09:31
  • @guettli regarding the first comment, on sourcing the `env` alone, this is because new lines are considered new variables, so it confuses everything. – fedorqui Aug 24 '16 at 09:42
  • 1
    That's because the output of env isn't meant to be a valid shell script, which is what `source` expects. So if any variable has spaces, newlines, dollar signs, etc, those will be parsed by the shell as if they were in any other script. The top answer using `declare -p` is the right way to do this. – Isaac Freeman Jul 03 '18 at 15:10