How to insert variables inside a string containing ""?

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.


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>