Skip to content
Advertisement

Parsing a config file inside shell script

I am trying to parse an ini file inside a shell script.

name.conf file:

Name1 : abc
Name2 : xyz

I could parse the values by the command

name1=$(awk '/^Name1/{print $3}' name.conf)
name2=$(awk '/^Name2/{print $3}' name.conf)

I wanted to know if there was some way by which I could group the contents of my config and parse it

name.conf file:

[Names]
abc
xyz
[Values]
blah
blahh

I just need the values in a shell array say names and print them like this

for var in $names
do
   echo $var
done
for var in $values
do
   echo $var
done

Advertisement

Answer

It’s easier than that. Just put all vars in a file (“vars”, for instance), in “name = value” format:

name1 = abc
name2 = xyz

Then in your main script, use “source” to load it:

#!/bin/bash
source vars

Or using period also works:

#!/bin/bash
. vars

Although that will only work if you run the script where the vars file is. Nagios use this approach to be able to run the script anywhere in the system:

#! /bin/bash
PROGNAME=`basename $0`
PROGPATH=`echo $0 | sed -e 's,[\/][^\/][^\/]*$,,'`
. $PROGPATH/vars

echo $name1

The output for that should be ‘abc’

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement