a recent version of bash
Last active
September 11, 2022 13:46
-
-
Save marshyon/5b2550a6de222c2b42795d321896f5c6 to your computer and use it in GitHub Desktop.
bash write and read simple JSON configuration data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| { "service3455": "42", "service3045": "89", "service2345": "33" } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| store_config() { | |
| if [[ -z $1 ]] && [[ -z $2 ]] ; then | |
| config_json_data=$(echo '{}' | jq '.') | |
| else | |
| config_json_data=$(echo $config_json_data | jq --arg v "$2" --arg k "$1" '.[$k] |= $v ') | |
| fi | |
| echo $config_json_data | |
| } | |
| lookup_config_value() { | |
| echo $config_json_data | jq --arg v $1 '.[$v]' | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env bash | |
| # import common functions for reading | |
| # and writing configuration | |
| . my_funcs.sh | |
| # read in configuration data from | |
| # configuration data file | |
| config_json_file="config.json" | |
| config_json_data=$(cat $config_json_file) | |
| # output data and a queried configuration | |
| # value | |
| echo "raw data is : "$config_json_data | |
| key_1="service3455" | |
| query=$(lookup_config_value $key_1 | sed "s/\"//g") | |
| echo "key_1 value is ${query}" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env bash | |
| # import common functions for reading | |
| # and writing configuration | |
| . my_funcs.sh | |
| # set up data to be saved | |
| key_1="service3455" | |
| key_2="service3045" | |
| key_3="service2345" | |
| value_to_be_saved=42 | |
| config_json_file="config.json" | |
| # initialise config_json_data | |
| config_json_data=$(store_config) | |
| # store key value data | |
| config_json_data=$(store_config $key_1 $value_to_be_saved) | |
| config_json_data=$(store_config $key_2 89) | |
| config_json_data=$(store_config $key_3 33) | |
| # save config data to a file | |
| echo $config_json_data > $config_json_file |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment