The issue is that you are using your variable in a single-quoted string. The shell will never expand variables in single quoted strings.
Another issue is that the value in $lorem
would not be properly XML encoded, so a value like <!--
would mess up the XML document and make it unparseable.
Instead, use jo
from https://jpmens.net/2016/03/05/a-shell-command-to-create-json-jo/ to create a JSON document and the yq
tool from https://kislyuk.github.io/yq/ to convert this to XML:
$ lorem=LOL
$ jo -p 'foo[@a]'=b 'foo[#text]'="$lorem" 'bar[@value]'=ipsum
{
"foo": {
"@a": "b",
"#text": "LOL"
},
"bar": {
"@value": "ipsum"
}
}
Then pass this through yq -x --xml-root=root .
to convert to XML and wrap it in a top-level root node called root
. Keys starting with @
will be turned into node attributes, and the value of the #text
key will be turned into the node's value.
$ jo 'foo[@a]'=b 'foo[#text]'="$lorem" 'bar[@value]'=ipsum | yq -x --xml-root=root .
<root>
<foo a="b">LOL</foo>
<bar value="ipsum"></bar>
</root>
With the value <!--
in $lorem
:
$ lorem='<!--'
$ jo 'foo[@a]'=b 'foo[#text]'="$lorem" 'bar[@value]'=ipsum | yq -x --xml-root=root .
<root>
<foo a="b"><!--</foo>
<bar value="ipsum"></bar>
</root>
Or, with the literal value $lorem
in the variable:
$ lorem='$lorem'
$ jo 'foo[@a]'=b 'foo[#text]'="$lorem" 'bar[@value]'=ipsum | yq -x --xml-root=root .
<root>
<foo a="b">$lorem</foo>
<bar value="ipsum"></bar>
</root>
yq --help
print nothing about xml support (but mentioned commands works). The recommended way to use xml related functionality is viaxq
executable. – eNca Feb 02 '24 at 08:37