【发布时间】:2014-11-27 20:45:15
【问题描述】:
我正在尝试使用 xmllint 来搜索一个 xml 文件并将我需要的值存储到一个数组中。这是我正在做的事情:
#!/bin/sh
function getProfilePaths {
unset profilePaths
unset profilePathsArr
profilePaths=$(echo 'cat //profiles/profile/@path' | xmllint --shell file.xml | grep '=' | grep -v ">" | cut -f 2 -d "=" | tr -d \")
profilePathsArr+=( $(echo $profilePaths))
return 0
}
在我的另一个功能中:
function useProfilePaths {
getProfilePaths
for i in ${profilePathsArr[@]}; do
echo $i
done
return 0
}
useProfilePaths
无论我是在命令行上手动执行命令还是从不同的函数调用它们作为包装脚本的一部分,函数的行为都会发生变化。当我可以从包装脚本中执行函数时,数组中的项目为 1,与我从命令行执行时相比,它是 2:
$ echo ${#profilePathsArr[@]}
2
回显时profilePaths的内容是这样的:
$ echo ${profilePaths}
/Profile/Path/1 /Profile/Path/2
我不确定 xmllint 调用的分隔符是什么。
当我从包装脚本调用函数时,for 循环的第一次迭代的内容如下所示:
for i in ${profilePathsArr[@]}; do
echo $i
done
第一个回声看起来像:
/Profile/Path/1
/Profile/Path/2
...第二个回显是空的。
谁能帮我调试这个问题?如果我能找出 xmllint 使用的分隔符是什么,也许我可以正确解析数组中的项目。
仅供参考,我已经尝试过以下方法,结果相同:
profilePaths=($(echo 'cat //profiles/profile/@path' | xmllint --shell file.xml | grep '=' | grep -v ">" | cut -f 2 -d "=" | tr -d \"))
【问题讨论】:
-
这里有什么问题?该循环确实遍历了两个数组元素。请发布一个不引用本地文件的完整脚本(以便我们可以在我们的机器上运行它),并清楚地解释为什么输出异常。
标签: arrays bash shell loops ifs