0

I have a script and a "config" file that pull variables from. I created the configuration file called config.cfg and used it in my script as such:

#! /bin/bash

if [ -f ./config.cfg ]
   then 
       source ./config.cfg
   else
       exit

The config files contains a number of different things like

title="Foo Bar - The Untold Story"
desc="This is a verbose description of Foo Bar's Untold Story"
author="S. Nafu"
date="01/01/1932"
image_url="./path_to_image/foo.bar.jpg"
image_link="http://www.foo.bar/foo_bar"

So far, eveything works because I can issue (in the script) the command:

echo $title

and get

Foo Bar - The Untold Story

What I am Trying to Accomplish

I want to create an XML file based on these fields and attributes. Ideally, want to parse the file and determine if the variable was declared, not if it has a value or not. So...here is the code I came up with:

function writeln 
{
   local attrib=$1
   local value=$2
   local fmt="%s%s%s\n" 
   printf $fmt "<$attrib>$value</$attrib>"
}

function writeChannel
{
    local fmt="%s\n"
    printf $fmt "<channel>"
    while read line
    do
        local xml_attrib=`echo $line | cut -d "=" -f1`
        local xml_value=`echo $line | tr -d '"' | cut -d "=" -f2`
        writeln $xml_attrib $xml_value

    done < config.cfg

}

When I execute the code, I get what is expected:

<title>Foo Bar - the Untold Story</title>
<desc>This is a verbose description of Foo Bar's Untold Story</desc>
....

Now, what I would like to do is use the variable "title" based on what I parsed (assume I don't know that the variables name is "title")

Basically, I want to do take the xml_attrib variable, concatenate a "$" to it and then get the contents. So, using the first line of my config.cfg file,

xml_attrib = "title"

How would I address that string as a var and say

echo $title

Any ideas?

Allan
  • 1,040

1 Answers1

1

In bash you can do indirection on a variable with the syntax ${!var}. E.g.

 a=x; b=a; echo "${!b}"  # gives you x

Other bash-isms you might like can replace eg:

xml_attrib=`echo $line | cut -d "=" -f1`
xml_value=`echo $line | tr -d '"' | cut -d "=" -f2`

by

xml_attrib=${line%%=*}
line=${line#*=}
xml_value=${line//\"/}

See bash(1), Parameter Expansion.

meuh
  • 51,383