2013-05-20 66 views
0

在bash腳本中我想將參數傳遞給xml命令的xmlstarlet工具。 這裏的腳本:bash將參數傳遞給xml ed

#!/bin/bash 
# this variable holds the arguments I want to pass 
ED=' -u "https://stackoverflow.com/a/@id" -v NEW_ID -u "https://stackoverflow.com/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 "https://stackoverflow.com/a/@id" -v NEW_ID -u "https://stackoverflow.com/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 "https://stackoverflow.com/a/@id" -v NEW_ID -u "https://stackoverflow.com/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

引號在擴展變量時沒有被處理,所以它們會被直接傳遞給'xml'命令。 – Barmar

+0

那麼我該如何解決這個問題? – hooch

回答

1

擺脫雙引號,因爲它們在展開變量後沒有被處理:

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

就是這樣!非常感謝! – hooch

3

bash中,最好使用數組來表示像這樣的選項列表。在這種情況下,它沒有區別,因爲ED中嵌入的項目都不包含空格。

#!/bin/bash 
# this variable holds the arguments I want to pass 
ED=(-u "https://stackoverflow.com/a/@id" -v NEW_ID -u "https://stackoverflow.com/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 "https://stackoverflow.com/a/@id" -v NEW_ID -u "https://stackoverflow.com/a/b" -v NEW_VALUE input.xml 
# here I pass them using the variable from above 
echo $IN | xml ed "${ED[@]}" 
+0

感謝您的這個提示!使生活更容易,字符串更容易:) – hooch