4

How can you do the equivalent of piping stdout to 'export'?

For background, I have a non-shell script that generates environment variables like so:

DATABASE_URL='someurl'
MAIL_KEY='key'
REDIS_URL='redis connection string'

I would like to take that output and execute it, something like: generate-env | xargs export

Unfortunately, export isn't a binary, and neither is eval. I would prefer not to have to write my output to a file and run it with source. Is this even possible?

7

You can use eval:

$ set -a
$ eval "$(command_that_generate_output)"
$ set +a
$ sh -c 'printf "%s\n" "$DATABASE_URL"'
someurl
  • He has a "non-shell script" generating the data. Could be a C program or anything. – Kusalananda Jun 23 '16 at 5:53
  • Doesn't matter. command_that_generate_output generates output that looks like shell commands. eval takes that output and actually treats it like shell commands. The -a option causes all those variables to be exported. Very elegant. – Edward Falk Jun 24 '16 at 2:21
  • Ahh, looking at the edit history, I see you were commenting on the first version of the answer, which was actually significantly different. – Edward Falk Jun 24 '16 at 2:23
3
$ export $( generate_env )

This would create exported variables using the data generated by generate_env.

Testing:

$ cat myenv
A=1
B=2
PIZZA=now

$ export $( cat myenv )

$ echo $PIZZA
now

$ echo $B
2
  • This answer changed my thinking so that I could approach the problem correctly. The goal should not be to "pipe output to" the export keyword, but rather to "surround and capture" the generating command's output with $( ) and feed that to export. My variation that worked for me was to say export MY_VAR=$(find | grep | xargs echo) and then $MY_VAR contains the output of that chain of commands. – DWoldrich May 25 '17 at 16:47

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.