env -0 dump environment. But how to load it?
Asked Answered
D

2

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

Deutzia answered 24/8, 2016 at 9:3 Comment(2)
what do you mean with load?Dipietro
@Dipietro With "load" I mean to set these variables in a different shell.Deutzia
C
23

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"
Caroleecarolin answered 24/8, 2016 at 12:35 Comment(1)
Yes, works even if newlines are in variables. Thank you.Deutzia
A
3

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
Asclepiadaceous answered 24/8, 2016 at 9:12 Comment(5)
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)Deutzia
The second solution (env -0) works, except: PROFILEREAD readonly variableDeutzia
@Deutzia uhms, this is because that variable of yours is set to readonly. There are some hacks on how to reset them...Asclepiadaceous
@Deutzia regarding the first comment, on sourcing the env alone, this is because new lines are considered new variables, so it confuses everything.Asclepiadaceous
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.Overflow

© 2022 - 2024 — McMap. All rights reserved.