Skip to content

Bash read array from config file

wordpress meta

title: 'Bash Read Array From Config File'
date: '2019-06-17T11:03:10-05:00'
status: publish
permalink: /bash-read-array-from-config-file
author: admin
excerpt: ''
type: post
id: 1360
category:
    - Bash
tag: []
post_format: []

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
</div>**Code**

<div class="wp-block-syntaxhighlighter-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 ````