Skip to content

Bash Read Array From Config File

I was recently needing to read values from a configuration file into bash and had some success with reading json with jq into bash array(s). However I resorted to a non json version which worked well. Something like this.

Config File

$cat array-simple.cfg
name=bucket name 1
exclude=folder1 folder 2

name=bucket name 2


$ cat
while read line; do
    if [[ $line =~ ^"["(.+)"]"$ ]]; then
        declare -A $arrname
    elif [[ $line =~ ^([_[:alpha:]][_[:alnum:]]*)"="(.*) ]]; then
        declare ${arrname}[${BASH_REMATCH[1]}]="${BASH_REMATCH[2]}"
done < array-simple.cfg

echo ${bucket1[name]}
echo ${bucket1[exclude]}

echo ${bucket2[name]}
echo ${bucket2[exclude]}

for i in "${!bucket1[@]}"; do echo "$i => ${bucket1[$i]}"; done

for i in "${!bucket2[@]}"; do echo "$i => ${bucket2[$i]}"; done


$ ./ 
bucket name 1
folder1 folder 2
bucket name 2
exclude => folder1 folder 2
name => bucket name 1
exclude => folder5
name => bucket name 2
Published inBash