1

I need to read data from a source and have to form a XML file using shell script. But first of all i don't know how to write multiple lines in a file using shell script

5

Use output redirection

echo '<fruit>'    > foo.xml   # overwrites
echo ' <apple />' >> foo.xml  # appends
echo '</fruit>    >> foo.xml  # appends

Or use a "here document"

cat <<EndXML > foo.xml
<fruit>
 <apple />
</fruit>
EndXML

Better yet is to use a scripting/programming language that has support for XML. I like Perl and XML::LibXML but you may prefer something else.

  • Thank you, Output redirection works perfectly for me. But all the tags ends up in a same line <fruit> <apple/> </fruit>. – newbie dev Dec 19 '11 at 14:42
  • When i used the second solution 'here document', i cant able to open up the xml document. am i doing anything wrong here? – newbie dev Dec 19 '11 at 15:04
  • @Vel: Yes, but I can't tell what you might be doing wrong without more information: Are you typing the command on the command line? Did you use cut & paste? Do you get an error message? If so, what was the error message exactly? – RedGrittyBrick Dec 19 '11 at 16:15
  • No i didn't do the cut and paste & not using the command line. I am saving the file on a remote location for both the operations. When i tried to open the file or try copying the file from the remote location to my desktop, it says 'Error Occurred'. Hope this helps – newbie dev Dec 19 '11 at 17:28
  • 1
    @Vel: I think you should ask about stylesheets and entity-escaping as a separate question. I suggest you provide plenty of detail about your operating system, tools and objectives. – RedGrittyBrick Dec 19 '11 at 17:46
2

The following creates a file named "file.txt" (or replaces the contents of the file if it already exists), and writes "foo" (without quotes) into it :

echo "foo" > file.txt

What you seem to look for is the following, appending the string "foo" (again, without quotes) in the file (and again, creating the file if it doesn't exist)

echo "foo" >> file.txt

So the following code will write three lines to "file.txt":

echo "foo" >> file.txt ; echo "bar" >> file.txt; echo "beer" >> file.txt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.