Wednesday, 23 April 2014

Simple configuration file for BASH scripts

Here are two functions that I frequently use in my BASH scripts to load configuration parameters:


The getVal fuction retreives a value corresponding to a key in a config file:

function getVal {
        # $1 is config file
        touch -a $1 #creates file if it does not exist
        # $2 is value to look for
        echo `grep "^$2" "$1" | sed "s#^$2=##"`
        #if info missing ask and add
}

usage: 
KEY_VALUE=$(getVal configfile.conf "KEY_NAME")

The addVal function checks if a variable already exists in a configuration file and prompts for input if it is missing:

function addVal {
        # $1 is config file
        touch -a $1 #creates file if it does not exist
        # $2 is value to ask if missing
        if [ -z "`grep "^$2" "$1" | sed "s#^$2=##"`" ] ; then
                read -p "Please enter $2: " addValVal
                echo "$2=$addValVal" >> $1
        fi
        #if info missing ask and add
}

usage:
addVal configfile.conf "KEY_NAME"



What a configuration file looks like:

KEY1=value1
KEY2=value2
KEY3=value3
KEY4=value4
KEY5=value5