2

I need to generate an XML file in bash(I am new to bash/scripting languages, despite working on C/C++/UNIX for some time). Right now, I am generating something like this, which is pretty flat

st='<'
et='>'
sl='/'
-------------------
stag() {
      text=$st$1$et 
      echo $text >> output_file
}
--------------------
etag() {
      text=$sl$1
      stag $text
}
--------------------
attr() {
      text=$1
      echo $text >> output_file
}
--------------------

#--Function Call
stag "tag"
attr "xml"
etag "tag"

--------------------

#--output
<tag>xml</tag>

In this, I feel there are lots of chance to make errors and after coding in C++ for so long, I think there should be a better structured way to code.... Any thoughts is appreciated.... or any material you think, I should learn first, plz post here.... Thanks...

howtechstuffworks
  • 1,824
  • 4
  • 29
  • 46
  • 3
    Doing this in Bash sounds like a very unforgiving task. I would strongly suggest using a language that has XML libraries, e.g. Python or Ruby. – Oliver Charlesworth Jun 04 '12 at 15:46
  • ^Hey oli, good to see you again...... I am just prototyping, I might need to use bash for the full project, for some legacy reasons.... Not sure yet though..... – howtechstuffworks Jun 04 '12 at 15:49
  • the question is, is there a better way of structuring an xml generator in bash... not necessarily it needs to be already written.... This code works perfectly fine.... Just making sure, if I am missing out anything... – howtechstuffworks Jun 04 '12 at 15:51

2 Answers2

3

You are looking for something like xmlstarlet. The depyx subcommand allows you to convert PYX markup into XML.

This may be sufficient for your prototyping purposes. If not, you'll probably need to look at a more full-featured XML library in Ruby, Python, or Perl.

Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
  • 1
    Yep. See also http://stackoverflow.com/questions/9898939/handling-long-edit-lists-in-xmlstarlet (which I've used when building large XML documents from shell scripts), and http://stackoverflow.com/a/9882528/14122 for an example of use. – Charles Duffy Jun 04 '12 at 17:51
0

It's usually easier to just quote your strings rather than having to use special variables for special characters, e.g., rather than

text=$st$1$et
echo $text

just use

echo "<$1>"

or printf "<%s>" $1

As for structure, bash does have arrays which you could perhaps use for attributes, but the only way to pass them to functions is by name, and then you have to jump through hoops to get the values:

a=(foo bar baz)
f() {
  eval printf "\${$1[1]}"
}
f a
=> bar
evil otto
  • 10,348
  • 25
  • 38