| name | json-config-loader-1-keyvalue-configuration-parsing |
| description | Sub-skill of json-config-loader: 1. Key=Value Configuration Parsing (+1). |
| version | 1.0.0 |
| category | _core |
| type | reference |
| scripts_exempt | true |
1. Key=Value Configuration Parsing (+1)
1. Key=Value Configuration Parsing
Parse simple key=value configuration files:
#!/bin/bash
CONFIG_FILE="${1:-config.conf}"
declare -A CONFIG
parse_config() {
local file="$1"
if [[ ! -f "$file" ]]; then
echo "Error: Config file not found: $file" >&2
return 1
fi
while IFS= read -r line || [[ -n "$line" ]]; do
[[ "$line" =~ ^[[:space:]]*# ]] && continue
[[ -z "${line// /}" ]] && continue
if [[ "$line" =~ ^([^=]+)=(.*)$ ]]; then
local key="${BASH_REMATCH[1]}"
local value="${BASH_REMATCH[2]}"
key="${key#"${key%%[![:space:]]*}"}"
key="${key%"${key##*[![:space:]]}"}"
value="${value#"${value%%[![:space:]]*}"}"
value="${value%"${value##*[![:space:]]}"}"
if [[ "$value" =~ ^\"(.*)\"$ ]] || [[ "$value" =~ ^\'(.*)\'$ ]]; then
value="${BASH_REMATCH[1]}"
fi
CONFIG["$key"]="$value"
fi
done < "$file"
}
get_config() {
local key="$1"
local default="${2:-}"
echo "${CONFIG[$key]:-$default}"
}
has_config() {
local key="$1"
[[ -v CONFIG[$key] ]]
}
parse_config "$CONFIG_FILE"
echo "Database: $(get_config 'database' 'default.db')"
echo "Port: $(get_config 'port' '8080')"
if has_config 'debug'; then
echo "Debug mode enabled"
fi
2. JSON Configuration with jq
Load and manipulate JSON configuration:
#!/bin/bash
check_jq() {
if ! command -v jq &> /dev/null; then
echo "Error: jq is required but not installed" >&2
echo "Install with: apt install jq (Ubuntu) or brew install jq (Mac)" >&2
exit 1
fi
}
load_json_config() {
local file="$1"
if [[ ! -f "$file" ]]; then
echo "{}"
return 1
fi
if ! jq empty "$file" 2>/dev/null; then
echo "Error: Invalid JSON in $file" >&2
echo "{}"
return 1
fi
cat "$file"
}
json_get() {
local json="$1"
local path=
default=
value
value=$( | jq -r 2>/dev/null)
[[ -z || == ]];
}
() {
json=
path=
| jq -r 2>/dev/null
}
() {
json=
path=
result
result=$( | jq -e 2>/dev/null)
[[ == ]]
}
check_jq
CONFIG_JSON=$(load_json_config )
DB_HOST=$(json_get )
DB_PORT=$(json_get )
DEBUG=$(json_get )
IFS= -r feature;
< <(json_get_array )