Shell script for copying environment variables into config.json?

26 views Asked by At

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:

#!/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.

1

There are 1 answers

2
Charles Duffy On BEST ANSWER

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):

if jq '. * env' <src/assets/config.json >src/assets/config.json."$$" ; then
  mv -- src/assets/config.json."$$" src/assets/config.json
else
  rm -f -- src/assets/config.json."$$"
fi