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>
share|improve this question
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 18 hours ago
up vote 6 down vote accepted

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.

share|improve this answer

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>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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