Bash – Section wise Variable Accessing from Config File

bashscriptingsedshell-script

I have one Configuration file with section wise data, as mentioned below. Using shell script accessing each variable. I am using sed command for that, Now I facing one problem like if I forget to configure one variable example:name [APP1] it will take [APP2] name.
Config File:

[APP1]
name=Application1
StatusScript=/home/status_APP1.sh
startScript=/home/start_APP1.sh
stopScript=/home/stop_APP1.sh
restartScript=/home/restart.APP1.sh

[APP2]
name=Application2
StatusScript=/home/status_APP2.sh
startScript=/home/start_APP2.sh
stopScript=/home/stop_APP2.sh
restartScript=/home/restart.APP2.sh
logdir=/log/APP2/
.
.
.
.
.
[APPN]
name=ApplicationN
StatusScript=/home/status_APPN.sh
startScript=/home/start_APPN.sh
stopScript=/home/stop_APPN.sh
restartScript=/home/restart.APPN.sh
logdir=/log/APPN

shell command using :

sed -nr "/^\[APP1\]/ { :l /^name[ ]*=/ { s/.*=[ ]*//; p; q;}; n; b l;}"

Is there any way to solve this problem, if some variable not configured under one section it through null or 0 as the variable value.

Best Answer

You can create a shell function like this:

printSection()
{
  section="$1"
  found=false
  while read line
  do
    [[ $found == false && "$line" != "[$section]" ]] &&  continue
    [[ $found == true && "${line:0:1}" = '[' ]] && break
    found=true
    echo "$line"
  done
}

You can then use printSection like a command, and pass in the section as a parameter like:

printSection APP2

To get your parameter, you can use a much simpler sed now, like:

printSection APP2 | sed -n 's/^name=//p'

This will be operating on stdin and writing to stdout. So if your example config file were called named /etc/application.conf, and you wanted to store the name of APP2 in a variable app2name, you could write this:

app2name=$(printSection APP2 | sed -n 's/^name//p/' < /etc/applications.conf)

Or, you could build the parameter part into the function and skip sed altogether, like this:

printValue()
{
  section="$1"
  param="$2"
  found=false
  while read line
  do
    [[ $found == false && "$line" != "[$section]" ]] &&  continue
    [[ $found == true && "${line:0:1}" = '[' ]] && break
    found=true
    [[ "${line%=*}" == "$param" ]] && { echo "${line#*=}"; break; }
  done
}

Then you would assign your var like this:

app2name=$(printValue APP2 name < /etc/applications.conf)
Related Question