Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Shell script for copying environment variables into config.json?

I’m tearing my hair out a bit at this. I’m trying to write a shell script which indexes through all environment variables, and then overrides variables in a config.json file.

I have a demo angular app which is running in a docker file and I’d like to be able to set config variables as environment variables. I know it’s not the safest approach but this code will never see production and the flexibility it grants me is desirable.

So far I have this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#!/bin/sh

env | while IFS= read -r line; do
  value=${line#*=}
  name=${line%%=*}
  
  jq --arg name "$name" --arg value "$value" '.[$name] = $value' src/assets/config.json > src/assets/config.json
done


jq . src/assets/config.json

The output json file keeps ending up empty though.

>Solution :

JQ has a built-in env function that refers to the current environment and exposes it as a dictionary.

Thus, all you need is:

jq -n env >src/assets/config.json

…or, to merge an existing config file to add new keys from the environment (and overwrite existing keys where they conflict):

jq '. * env' <src/assets/config.json >src/assets/config.json."$$" \
  && mv src/assets/config.json."$$" src/assets/config.json
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading