bash reading config files

This was based in my audiabus code for pulling configuration data (which was then adapted again to work on my IPMI code):

function __config__ () {
        i=0
        while read line; do
                [[ ${line} =~ ^(.*)[=](.*)$ ]] && var=${BASH_REMATCH[1]} && val=${BASH_REMATCH[2]}
                __config__var[${i}]=${var}
                __config__val[${i}]=${val}
                i=$[${i}+1]
        done < ${1}
}

I think it’s a pretty decent solution for pulling config file information in the format:

option=value
option=value

You can then run checks against __config__var[@] and __config__val[@]. An example of this would be:

test.cfg

test1="Some random thing"
test2="Another thing of random"
test3="I will probably fail"

test.sh

#!/bin/bash

function __config__ () {
        i=0
        while read line; do
                [[ ${line} =~ ^(.*)[=](.*)$ ]] && var=${BASH_REMATCH[1]} && val=${BASH_REMATCH[2]}
                __config__var[${i}]=${var}
                __config__val[${i}]=${val}
                i=$[${i}+1]
        done < ${1}
}

__config__ "./test.cfg"

i=0
j=${#__config__var[@]}

while [[ ${i} -lt ${j} ]]; do
        case ${__config__var[${i}]} in
                "test1") echo -n "It looks like you set test1 as: " ;;
                "test2") echo -n "On the other hand, you have test2 as: " ;;
                *) echo "I don't know what '" ${__config__var[${i}]} "' is supposed to mean..."; exit 0 ;;
        esac
        echo "${__config__val[${i}]}"
        i=$[${i}+1]
done

This should give you the result:

~$ bash test.sh 
It looks like you set test1 as: "Some random thing"
On the other hand, you have test2 as: "Another thing of random"
I don't know what ' test3 ' is supposed to mean...

You still obviously have to loop through the tests for each variable, but it gives the flexibility of only having one set of config reading lines which you can apply multiple times.

Imported from 2013/07/04

Import Note: I actually still use a similar set up in my modern scripts, though both the output array is different. I’ll have to do a new post on it.