Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
up vote 3 down vote accepted

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)"
share|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.

share|improve this answer
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
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
never mind; misunderstanding of the commentary. – Josh McGee Jul 23 '13 at 19:57

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.