Skip to content

Instantly share code, notes, and snippets.

@x3rAx
Last active January 30, 2020 10:41
Show Gist options
  • Save x3rAx/e132b6ca19094808d3dad6b0891d76ca to your computer and use it in GitHub Desktop.
Save x3rAx/e132b6ca19094808d3dad6b0891d76ca to your computer and use it in GitHub Desktop.
bash - loadConfig
loadConfig() {
local var_name="$1"
local config_file="$2"
declare -A config
local config=()
local line_num=0
while read -r line; do
#echo ">$line<"
let line_num++
if [[ $line =~ ^$|^\# ]]; then
continue
fi
# sq-str: single-quote-string
# dq-str: double-quote-string
# - - - - - - - - ( key ) - - - - - (=) - - - - - - -( sq-str ) - - ( dq-str )- -( boolean | numbers )
if [[ ! $line =~ ^([a-zA-Z0-9_.-]+)[[:space:]]*=[[:space:]]*(\'(([^\']|\\\')*)\'|\"(([^\"]|\\\")*)\"|(true|false|(0|[1-9][0-9]*)(\.[0-9]+){0,1}))$ ]]; then
echo >&2 "ERROR: ${SCRIPT_NAME}: Invalid config: ${config_file}:${line_num}"
exit 1
fi
local key="${BASH_REMATCH[1]}"
local string_single_quote="${BASH_REMATCH[3]//\\\'/\'}"
local string_double_quote="${BASH_REMATCH[5]//\\\"/\"}"
local other_vaues="${BASH_REMATCH[7]}"
local value="${string_single_quote}${string_double_quote}${other_vaues}"
config[$key]="$value"
#for x in "${BASH_REMATCH[@]}"; do
# echo "|$x|"
#done
done < "$config_file"
local serialized="$(declare -p config)"
local serialized_data="${serialized#*=}"
declare -gA "${var_name}=${serialized_data}"
}
loadConfig CONFIG <(cat <<EOF
# Comments are ignored as well as empty lines
# Indents don't matter
hello = "config"
hello.text = "It is okay to use \"escaped\" quotes."
hello.text2 = 'This also applies to \'single quoted\' strings.'
wow = true
pi = 3.1415
THE_ANSWER = 42
EOF
)
echo "Hello, ${CONFIG[hello]}!"
echo "${CONFIG[hello.text]}"
echo "${CONFIG[hello.text2]}"
echo "${CONFIG[wow]}"
echo "${CONFIG[pi]}"
echo "${CONFIG[THE_ANSWER]}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment