How to output env as runnable shell script

You can trivially output your environment as a runnable shell script with

env > my_env 

... later in another script ...

 set -a source my_env 

This works for the most trivial cases, but fails if any special characters or spaces are in env.

How can I fix the above script so that it works with a file like a='"'"'" ?

+8
bash
source share
3 answers

Use set instead of env :

 β—‹ β†’ set | grep LESS LESS=-R LESSCLOSE='/usr/bin/lesspipe %s %s' LESSOPEN='| /usr/bin/lesspipe %s' β—‹ β†’ env | grep LESS LESS=-R LESSOPEN=| /usr/bin/lesspipe %s LESSCLOSE=/usr/bin/lesspipe %s %s 

Thanks to this similar question, we can do this to get JUST environment variables as follows:

 β—‹ β†’ (set -o posix; set) | grep LESS LESS=-R LESSCLOSE='/usr/bin/lesspipe %s %s' LESSOPEN='| /usr/bin/lesspipe %s' 

Try this hippo, which should print only the difference with the "pristine" shell. YMMV:

 diff --old-line-format='%L' --unchanged-line-format= --new-line-format= \ <(bash -c 'set -o posix; set' | sort) \ <(env -i bash -c 'set -o posix; set' | sort) 
+4
source share

The following values ​​use bash printf %q to correctly exclude values ​​regardless of their contents. It is guaranteed to handle literally any possible value - quotation marks, newlines, etc., while the shell highlighting its output, bash, and while the operating system used supports the /proc/self/environ tool, first provided by Linux, to emit the contents of the environment as a stream limited to NUL. It uses special quoting forms such as $'\n' as and when necessary, so its output cannot be honored with pure POSIX interpreters.

 #!/usr/bin/env bash while IFS= read -r -d '' kvname; do k=${kvname%%=*} v=${kvname#*=} printf '%q=%q\n' "$k" "$v" done </proc/self/environ 

Please note that you will need to display the source code, and not run it as an external executable file if you want to change the current shell environment. If you do not want set -a before searching, add the export lead to the format string.

+4
source share

The simplest solution seems to be

 export -p > my_env 
+3
source share

All Articles