24

I want to construct an xml string by inserinting variables:

str1="Hello"
str2="world"

xml='<?xml version="1.0" encoding="iso-8859-1"?><tag1>$str1</tag1><tag2>$str2</tag2>'

echo $xml

The result should be

<?xml version="1.0" encoding="iso-8859-1"?><tag1>Hello</tag1><tag2>world</tag2>

But what I get is:

<?xml version="1.0" encoding="iso-8859-1"?><tag1>$str1</tag1><tag2>$str2</tag2>

I also tried

xml="<?xml version="1.0" encoding="iso-8859-1"?><tag1>$str1</tag1><tag2>$str2</tag2>"

But that removes the inner double quotes and gives:

<?xml version=1.0 encoding=iso-8859-1?><tag1>hello</tag1><tag2>world</tag2>
  • 2
    An XML document cannot have 2 top-level tags. Also, it's 2016, I would strongly recommend using utf-8, not iso-8859-1. – Celada Dec 25 '16 at 13:21
27

You can embed variables only in double-quoted strings.

An easy and safe way to make this work is to break out of the single-quoted string like this:

xml='<?xml version="1.0" encoding="iso-8859-1"?><tag1>'"$str1"'</tag1><tag2>'"$str2"'</tag2>'

Notice that after breaking out of the single-quoted string, I enclosed the variables within double-quotes. This is to make it safe to have special characters inside the variables.

Since you asked for another way, here's an inferior alternative using printf:

xml=$(printf '<?xml version="1.0" encoding="iso-8859-1"?><tag1>%s</tag1><tag2>%s</tag2>' "$str1" "$str2")

This is inferior because it uses a sub-shell to achieve the same effect, which is an unnecessary extra process.

As @steeldriver wrote in a comment, in modern versions of bash, you can write like this to avoid the sub-shell:

printf -v xml ' ... ' "$str1" "$str2"

Since printf is a shell builtin, this alternative is probably on part with my first suggestion at the top.

6

Variable expansion doesn't happen in single quote strings.

You can use double quotes for your string, and escape the double quotes inside with \. Like this :

xml="<?xml version=\"1.0\" encoding=\"iso-8859-1\"?><tag1>$str1</tag1><tag2>$str2</tag2>"

The result output :

<?xml version="1.0" encoding="iso-8859-1"?><tag1>hello</tag1><tag2>world</tag2>

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.