Search code examples
bashxmlstarlet

bash passing parameters to xml ed


Inside a bash script I want to pass arguments to the xml ed command of the xmlstarlet tools. Here's the script:

#!/bin/bash
# this variable holds the arguments I want to pass
ED=' -u "/a/@id" -v NEW_ID -u "/a/b" -v NEW_VALUE'
# this variable holds the input xml
IN='
<a id="OLD_ID">
    <b>OLD_VALUE</b>
</a>
'
# here I pass the arguments manually
echo $IN | xml ed -u "/a/@id" -v NEW_ID -u "/a/b" -v NEW_VALUE input.xml
# here I pass them using the variable from above
echo $IN | xml ed $ED

Why does the first call work, ie it gives the desired result:

# echo $IN | xml ed -u "/a/@id" -v NEW_ID -u "/a/b" -v NEW_VALUE input.xml
<?xml version="1.0"?>
<a id="NEW_ID">
  <b>NEW_VALUE</b>
</a>

While the second call does not work, ie it gives:

# echo $IN | xml ed $ED
<?xml version="1.0"?>
<a id="OLD_ID">
  <b>OLD_VALUE</b>
</a>

Solution

  • Get rid of the double quotes, because they're not processed after expanding variables:

    ED=' -u /a/@id -v NEW_ID -u /a/b -v NEW_VALUE'