Copied code from the bash framework and add json based config file support
This commit is contained in:
parent
3ccf356c11
commit
6d893a43a6
3 changed files with 78 additions and 10 deletions
45
config.bash
Normal file
45
config.bash
Normal file
|
@ -0,0 +1,45 @@
|
|||
#!/bin/bash
|
||||
|
||||
JSON_FILE="config.json"
|
||||
|
||||
read_json() {
|
||||
local JSON_FILE="$1"
|
||||
local SECTION="$2"
|
||||
local KEY="$3"
|
||||
|
||||
jq -r ".${SECTION}.${KEY}" "$JSON_FILE"
|
||||
}
|
||||
|
||||
# Function to write a value to a JSON configuration file
|
||||
write_json() {
|
||||
local JSON_FILE="$1"
|
||||
local SECTION="$2"
|
||||
local KEY="$3"
|
||||
local VALUE="$4"
|
||||
|
||||
# It important to check if the file is valid otherwise stuff breaks
|
||||
if ! jq -e . < "$JSON_FILE" > /dev/null 2>&1; then
|
||||
echo "Error: JSON file is not valid JSON."
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Using jq to set the value. The original file is replaced with a new file with the updated value.
|
||||
jq ".${SECTION}.${KEY} = \"$VALUE\"" "$JSON_FILE" > "temp.json" && mv "temp.json" "$JSON_FILE"
|
||||
|
||||
}
|
||||
|
||||
create_json() {
|
||||
local JSON_FILE="$1"
|
||||
echo '{"bashini": "new"}' | jq '.' > "$JSON_FILE" # well we need something in there
|
||||
write_json "$JSON_FILE" "restic" "password" "backupsarefun" # for the openwrt backup script here for testing
|
||||
}
|
||||
|
||||
check_json() {
|
||||
local JSON_FILE="$1"
|
||||
if [ ! -f "$JSON_FILE" ]; then
|
||||
create_json "$JSON_FILE"
|
||||
fi
|
||||
}
|
||||
|
||||
check_json "$JSON_FILE"
|
||||
|
Loading…
Add table
Add a link
Reference in a new issue