Saturday, February 15, 2014

Parsing a Configuration File Using Bash

Here's a simple way to use a configuration file with a Bash shell script.

#Specify configuration file at command prompt
CONF_FILE=$1

#Read variables from conf file
ADDRESS=$(grep ADDRESS $CONF_FILE | awk -F= '{ print $2 }')
USERNAME=$(grep USERNAME $CONF_FILE | awk -F= '{ print $2 }')
FILETODOWNLOAD=$(grep FILETODOWNLOAD $CONF_FILE | awk -F= '{ print $2 }')
DOWNLOADPATH=$(grep DOWNLOADPATH $CONF_FILE | awk -F= '{ print $2 }')
LOGPATH=$(grep LOGPATH $CONF_FILE | awk -F= '{ print $2 }')
LOGRETENTION=$(grep LOGRETENTION $CONF_FILE | awk -F= '{ print $2 }')

Configuration file:

ADDRESS=192.168.88.20
USERNAME=sheldon
FILETODOWNLOAD=Downloads/*download.txt
DOWNLOADPATH=.
LOGPATH=logs/
LOGRETENTION=-1

The script uses grep and awk to parse the configuration and assign the directives in it to the variables in the script.

No comments:

Post a Comment