Bash – Export Environment Variables with Correct Escaping

bashdashenvironment-variablesshell

I want to export some environment variables which I set in a dash script to a file:

myvariable="line 1

LINE=3
some characters: # \" \$
line 5"
myvariable2="abc"
export myvariable myvariable2

expected result (a usable script):

declare -x myvariable="line 1

LINE=3
some characters: # \" \$
line 5"
declare -x myvariable2="abc"

The result is what I get using the export command. But it exports all envvars and doesn't allow filtering. Because of the multi-line character of the variable, greping the result is not possible.

In contrast, the printenv command allow to output only a selection of variables, but it doesn't care about escaping and it doesn't output the variable names in this use case.

Best Answer

In zsh or yash.

export -p myvariable myvariable2

would work as you'd expect.

Otherwise, in bash, you can still do:

for var in myvariable myvariable2; do
  printf 'export %s=%q\n' "$var" "${!var}"
done

POSIXly, you can do the quoting by hand using awk:

awk -v q="'" '
  function escape(v) {
    gsub(q, q "\\" q q, v)
    return q v q
  }
  BEGIN {
    for (i = 1; i < ARGC; i++)
      print "export " ARGV[i] "=" escape(ENVIRON[ARGV[i]])
  }' myvariable myvariable2

For fun, a hacky solution that works in some shells (bash, zsh, mksh, ksh93, not yash nor dash):

 (PS4=; set -x; export "myvariable=$myvariable") 2>&1
Related Question