Take the 2-minute tour ×
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.

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
foo=a
baraz

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

2 Answers 2

up vote 3 down vote accepted

You could do:

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

printvars

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
    do
        printf '%s=%q\n' "$name" "$value"
    done
}

Example session:

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

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

Your Answer

 
discard

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.