I'm working on a bash script that supposed to read a config file and use it later. The config file looks like this:
[config]
key1=value1
key2=value2
key3=value3
I found this question helpful while figuring out how to parse the file: Bash Parse Arrays From Config File
The relevant code from the answer is this:
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
This code works great when I use it as a pure script. However, if I wrap it with a function, the script terminates after reading the first key (I used set -o xtrace to find this out).
Why this code:
read_config() {
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 < $1
}
read_config config.conf
The output looks like this:
++ read_config
++ read line
++ [[ [config] =~ ^\[(.+)]$ ]]
++ arrname=config
++ declare -A config
++ read line
++ [[ local=127.0.0.1 =~ ^\[(.+)]$ ]]
++ [[ local=127.0.0.1 =~ ^([_[:alpha:]][_[:alnum:]]*)=(.*) ]]
++ declare 'config[local]=127.0.0.1'
Segmentation fault (core dumped)
Causes an error(Command terminated), while the first, pure-script, isn't?
(The title is far from perfect, I not sure how to describe it more accurately.)
Thanks!