How to insert variables inside a string containing ""?
Solution 1
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.
Solution 2
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>
Related videos on Youtube
supermario
Updated on September 18, 2022Comments
-
supermario almost 2 years
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>