6

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.

  • What kind of output do you expect to see? export and printenv are both returning your variables as you defined them. Did you want newlines to be converted to something else? – Jeff Schaller Oct 5 '15 at 15:50
  • The output should be a usable script. printenv will create garbage, printenv myvariable myvariable2 doesn't output a script, export exports the full environment including PATH etc and not only myvariable and myvariable2 – Daniel Alder Oct 5 '15 at 15:54
2

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
  • Nice answer. I use awk in my script because it's dash and moving to zsh is not an option. I'm a bit disappointed of bash/dash. Maybe I should really consider switching to another shell... – Daniel Alder Oct 5 '15 at 16:21

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.