The following uses bash's printf %q
to escape values correctly regardless of their content. It's guaranteed to handle literally any value possible -- quotes, newlines, etc -- so long as the shell sourcing its output is bash, and so long as the operating system in use supports the /proc/self/environ
facility first provided by Linux to emit the contents of the environment as a NUL-delimited stream. It uses special quoting forms such as $'\n'
as and where appropriate, so its output may not be honored by 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
Note that you'll want to source the output, not run it as an external executable, if you want your current shell's environment to change. If you don't want to set -a
before sourcing, add a leading export
to the format string.