Configuration file to input values in bash script

Most of the time bash script need user input values to generate the data that is presented to user. There are many ways to accept user data in bash like reading data interactively, getting from parameters etc. But there are some situations where bash always need a set of data to generate the output. It will be a burden on the user to input the same data again and again, each time he executes the script. In that situations, storing the value in a configuration file will help. That file can be edited by user, if he requires to pass another set of data. You can see this concept in the BSD style init scripts, were boot parameters are stored in a centralized file like rc.conf.

Today I faced a problem with the script in which I was trying to produce colorized output based on the user preferences. It is unnecessary to ask user each time for his color preference. Instead of that he can just put the input in a configuration file and ask the script to read it. Another option is to hard code the color values in the script itself, but that will make it difficult for the user, if he want to change the color preference later.

The following script uses the configuration file to change the color of the text.

#!/bin/bash
#Generate color based on configuration file values
if [ ! -f ./color.conf ]
then
echo "Configuration file not found. Exiting!!"
exit
fi
. ./color.conf
getcolor()
{
COMPONENT=$1
case $COMPONENT in
Black)COLOR=30
MODE=0
;;
Red)COLOR=31
MODE=0
;;
Green)COLOR=32
MODE=0
;;
*);;
esac
}
getcolor $TITLE
echo -e "\033[${MODE};${COLOR}mTitle text\033[0m"
getcolor $DATA
echo -e "\033[${MODE};${COLOR}mData text\033[0m"
getcolor $LINK
echo -e "\033[${MODE};${COLOR}mLink text\033[0m"

By changing the value in the following configuration file, user can change the color of each text component.

#color codes
TITLE=Black
DATA=Red
LINK=Green

It is always good to have a global configuration file and local one for the script. Usually in linux global configuration file will reside in /etc and local will be a hidden file in user’s home directory. Normal users can use the configuration file in the home directory to override the values in the global configuration file.

Share
This entry was posted in bash, imdb movie fetcher, Linux, scripting. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>