How to Read Parameters from a JSON File in BASH Script?


bash-shellshock How to Read Parameters from a JSON File in BASH Script?

bash-shellshock

The parameters can be passed as command line to the shell scripts as $1, $2 etc. However, if there are many parameters, passing via command line is not ideal and convenient.

We can utilize the jq command/tool to parse a JSON string. First, lets test if the jq is installed:

#!/bin/bash

test_json=$(echo "{ }" | jq)
if [ "$test_json" != "{}" ]; then
        echo "jq not installed"
        exit 1
fi

Then, we let the $1 passed as the first command line parameter – which points to an external JSON file:

config=$1

if [ ! -f "$config" ]; then
        echo "config file $config not valid"
        exit 2
fi

Then, we need to store the file content in a shell variable:

json=$(cat "$config")

And then, we declare a shell function (BASH) to read the parameter in a JSON string:

readJsonConfig() {
        echo $json | jq -r $1
}

Given the following JSON file:

{
        "data": {
                "x": "Hello, world!"
        }
}

The following prints “Hello, world!”

echo $(readJsonConfig ".data.x")

As you can see, we use the single dot “.” to follow the path in JSON. Here is the complete BASH source code:

#!/bin/bash

test_json=$(echo "{ }" | jq)
if [ "$test_json" != "{}" ]; then
        echo "jq not installed"
        exit 1
fi

config=$1

if [ ! -f "$config" ]; then
        echo "config file $config not valid"
        exit 2
fi

json=$(cat $config)

readJsonConfig() {
        echo $json | jq -r $1
}

echo $(readJsonConfig ".data.x")

We can use envsubst command to inject the environmental variables in JSON so that we can have dynamic fields (env variables) in JSON such as $PASSWORD. We need to change to the following bash function to read the JSON into BASH string.

json=$(envsubst < "$config")

–EOF (The Ultimate Computing & Technology Blog) —

411 words
Last Post: Teaching Kids Programming - Introduction to SQL and the SELECT
Next Post: Teaching Kids Programming - Most Common SQL keywords (Select, Update, Insert, Delete)

The Permanent URL is: How to Read Parameters from a JSON File in BASH Script? (AMP Version)

Leave a Reply