在bash脚本中,我想将参数传递给xmlstarlet工具的xml ed命令。 这是脚本:
#!/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
为什么第一次调用有效,即它给出了所需的结果:
# 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>
虽然第二个电话不起作用,即它给出:
# echo $IN | xml ed $ED
<?xml version="1.0"?>
<a id="OLD_ID">
<b>OLD_VALUE</b>
</a>
答案 0 :(得分:3)
在bash
中,最好将数组用于此类选项列表。在这种情况下,它没有什么区别,因为ED
中嵌入的项都没有包含空格。
#!/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[@]}"
答案 1 :(得分:1)
删除双引号,因为它们在扩展变量后不会被处理:
ED=' -u /a/@id -v NEW_ID -u /a/b -v NEW_VALUE'