Blog-o de Ganso
Publicado en

Mini post: JSON config for scripts

Have you ever wondered if it is possible to configure a script using a json file? Me neither!

It seems to be possible using jq. You just need to parse the configuration file and use the read variables in your script:

{
    "message" : "Hello World!",
    "times" : 3
}
config.json
export CONFIGFILE=config.json
message=$(jq -r '.message' $CONFIGFILE)
times=$(jq -r '.times' $CONFIGFILE)

for i in $(seq 1 $times); do
    echo $message
done
script.sh

With a setup like this, you can alter the behavior of the script by modifying its configuration:

> chmod +x ./script.sh
> .script.sh | nl

     1	Hello World!
     2	Hello World!
     3	Hello World!

> sed -i "s/Hello/Bye/g;s/3/6/g" config.json
> script.sh | nl

     1	Bye World!
     2	Bye World!
     3	Bye World!
     4	Bye World!
     5	Bye World!
     6	Bye World!

Is this useful? I don't know (ಠ_ಠ). Also, take a look a this great intro to jq I found some time ago.