In Bash 4.2.25, the set and env output is not escaped, so shell escapes and any non-printable characters won't be copy-pasteable. Take for example this shell session:

$ export foo=$'a\nbar=\baz'
$ env | grep -A 1 foo

Ditto for for example colors - They are printed literally, and can mess up the terminal. How do you print all variables with their values in a way that the output can be copied and pasted to give the same environment?*

* Obviously with the standard caveats about readonly variables, special variables like $_ and the like.


You could do:

printvars() (
  eval 'declare() { printf declare; printf " %q" "$@"; echo; }'"
        $(declare -p)"


That could be easily extended to omit read-only variables like:

printvars() (
  eval 'declare() {
          [[ $1 = *r* ]] && return
          printf declare; printf " %q" "$@"; echo
        $(declare -p)"
| improve this answer | |
  • Redefine declare in a subshell to print its own output. Nice! – l0b0 Apr 16 '13 at 8:59
escaped_env() {
    cat /proc/self/environ | while IFS== read -r -d '' name value
        printf '%s=%q\n' "$name" "$value"

Example session:

$ export foo=$'a\nbar=\baz'
$ escaped_env | grep foo

This works, but only for exported variables, and set doesn't seem to have a ␀-separator option.

FYI, the /proc filesystem is not a POSIX.1-2008 feature, and it looks like only Linux implements /proc/self/environ. If your OS doesn't have this file, you may want to use env --null before the pipe.

| improve this answer | |
  • 3
    If your env does not support --null but you're on Linux, you can use cat /proc/self/environ instead. – Stéphane Chazelas Apr 15 '13 at 20:55
  • It looks like /proc/self/environ is not updated when exporting more variables. – l0b0 Apr 16 '13 at 8:37
  • 1
    Hence the use of cat (which in this case is not a UUOC) to pass that updated environment along the execution of a new command. – Stéphane Chazelas Apr 16 '13 at 8:54

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.