0

在 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>
4

2 回答 2

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[@]}"
于 2013-05-20T23:28:25.703 回答
1

去掉双引号,因为它们在扩展变量后没有被处理:

ED=' -u /a/@id -v NEW_ID -u /a/b -v NEW_VALUE'
于 2013-05-20T23:10:28.977 回答