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 ]
       source ./config.cfg

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"

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
        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?


1 Answer 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`



See bash(1), Parameter Expansion.

  • Note that while ${var%%} and ${var#*=} are standard, ${line//\"/} is a kshism (and zsh and bash). Commented Aug 31, 2015 at 10:16

Not the answer you're looking for? Browse other questions tagged .