Bash Parse Arrays From Config File Bash Parse Arrays From Config File bash bash

Bash Parse Arrays From Config File


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]}"    fidone < config.conf$ echo ${array0[value1]}asdf$ echo ${array1[value2]}5678$ for i in "${!array0[@]}"; do echo "$i => ${array0[$i]}"; donevalue1 => asdfvalue2 => jkl$ for i in "${!array1[@]}"; do echo "$i => ${array1[$i]}"; donevalue1 => 1234value2 => 5678


One eval-free, 100% pure Bash possibility:

#!/bin/bashdie() {   printf >&2 "%s\n" "$@"   exit 1}aryname=''linenb=0while read line; do   ((++linenb))   if [[ $line =~ ^[[:space:]]*$ ]]; then      continue   elif [[ $line =~ ^\[([[:alpha:]][[:alnum:]]*)\]$ ]]; then      aryname=${BASH_REMATCH[1]}      declare -A $aryname   elif [[ $line =~ ^([^=]+)=(.*)$ ]]; then      [[ -n aryname ]] || die "*** Error line $linenb: no array name defined"      printf -v ${aryname}["${BASH_REMATCH[1]}"] "%s" "${BASH_REMATCH[2]}"   else      die "*** Error line $linenb: $line"   fidone

Reads on standard input. If you want to read from a file, change the done by:

done < "filename"

Lines of the form

space and funnŷ sÿmbòl=value that will have an equal sign: look = it's funny

are allowed


You can declare array in bash scripts with

declare -a <array_name>=(value1 value2 value 3)

Then you can use them like this

echo ${<array_name>[index]}

Edit:

Ok, to construct arrays from config file. I would recommend to have a different file for each array you would like to create.

So here are the steps

1.config file (create a file and place your values in it)

100200300

2.script file (read values from file and prepare an array)

    array=()    #setup array    while IFS=$'\n' read -a config    do      array+=(${config})    done < file_name    #access values    echo ${array[0]}    echo ${array[1]}

IFS denotes the delimiter
-a specifies the array name you want to extract to, so that you can access them inside the while loop.