0

I have some environment variables declared in a YAML file like:

runtime: python37

env_variables:
  API_URL: 'https://fake.api.com/'
  API_USERNAME: 'fake@email.com'
  API_PASSWORD: 'Passwooord'

I would like to export these to environment variables with a script, I can echo the correct syntax but I'm still unable to export them.

sed -nr '/env_variables:/,$ s/  ([A-Z_]+): (.*)/\1=\2/ p' app.yaml | while read assign; do echo $assign; done

This is different that this as in my case the variable name is passed trough the pipe as well.

neurino
  • 1,819
  • 3
  • 19
  • 25
  • @muru in my case you also have variable names in the pipe, which is a step further from read a b < <(echo 1 2 3 4 5) where a and b are after the pipe. Could you please post a working case with my example? – neurino Sep 05 '19 at 13:05
  • What difference does that make? What part of it are you having trouble adapting to your case? – muru Sep 05 '19 at 13:06
  • @muru the part where I assign to a variable whose name is in another variable — I'd be happy to accept your answer straight away if you post it below – neurino Sep 05 '19 at 13:11
  • export "$name=$value", printf -v "$name" "%s" "$value", read "$name" <<<"$value", ... (Pick one) – muru Sep 05 '19 at 13:15
  • I'm not near a PC, can't test an answer now. I can provide what I think should work – muru Sep 05 '19 at 13:15

1 Answers1

2

Assuming the sed command correctly outputs lines of the form var=value, you can do:

while read assign; do
 export "$assign"; 
done < <(sed -nr '/env_variables:/,$ s/  ([A-Z_]+): (.*)/\1=\2/ p' app.yaml)

Or, if you don't need to export, and the input is reasonably safe (no shell syntax),

. <(sed -nr '/env_variables:/,$ s/  ([A-Z_]+): (.*)/\1=\2/ p' app.yaml)
muru
  • 72,889
  • Thanks, the second works like a charm! The first works somehow, keeping quotes in the value of the variable, e.g. echo $API_PASSWORD prints 'Passwooord' – neurino Sep 05 '19 at 13:55
  • The sed command needs to eliminate the quotes there (the shell doesn't interpret quotes after variable expansion) for the first. – muru Sep 05 '19 at 13:57