Bash Parse Arrays From Config File
arrays, bash, configuration-files, linux, parsing
Solution
with bash v4, using associative arrays, store the properties from the config file as actual bash variables:
$ while read line; do
if [[ $line =~ ^"["(.+)"]"$ ]]; then
arrname=${BASH_REMATCH[1]}
declare -A $arrname
elif [[ $line =~ ^([_[:alpha:]][_[:alnum:]]*)"="(.*) ]]; then
declare ${arrname}[${BASH_REMATCH[1]}]="${BASH_REMATCH[2]}"
fi
done < config.conf
$ echo ${array0[value1]}
asdf
$ echo ${array1[value2]}
5678
$ for i in "${!array0[@]}"; do echo "$i => ${array0[$i]}"; done
value1 => asdf
value2 => jkl
$ for i in "${!array1[@]}"; do echo "$i => ${array1[$i]}"; done
value1 => 1234
value2 => 5678
Problem
I need to have an array for each "section" in the file containing: ``` [array0] value1=asdf value2=jkl [array1] value1=1234 value2=5678 ``` I want to be able to retrieve these values like this: ``` echo ${array0[value1]} echo ${array0[value2]} echo ${array1[value1]} echo ${array1[value2]} ``` Any thoughts on how to accomplish this? (Explanations would be a bonus) I've already read these anwsers but none do exactly what I want to do. Read a config file in BASH without using "source" BASH Parsing variables from config file Array like data structure in bash (config file)?