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
[bucket1]
name=bucket name 1
exclude=folder1 folder 2
[bucket2]
name=bucket name 2
exclude=folder5
Code
$ cat array-simple.sh
#!/bin/bash
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 < 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
Run
$ ./array-simple.sh
bucket name 1
folder1 folder 2
bucket name 2
folder5
exclude => folder1 folder 2
name => bucket name 1
exclude => folder5
name => bucket name 2