EVAL在shell脚本给错误
问题描述:
我的XML文件(in.xml)是这样的:EVAL在shell脚本给错误
<Users>
<Host>
<hostAddress>180.144.226.47</hostAddress>
<userName>pwdfe</userName>
<password>hjitre</password>
<instanceCount>2</instanceCount>
</Host>
<Host>
<hostAddress>180.144.226.87</hostAddress>
<userName>trrrer</userName>
<password>jhjjhhj</password>
<instanceCount>3</instanceCount>
</Host>
</Users>
我的shell脚本:
#!/bin/ksh
for tag in hostAddress userName password instanceCount
do
OUT=`grep $tag in.xml | tr -d '\t' | sed 's/^<.*>\([^<].*\)<.*>$/\1/' `
# This is what I call the eval_trick, difficult to explain in words.
eval ${tag}=`echo -ne \""${OUT}"\"`
done
# So let's stuff the obtained results into 4 different Arrays
H_ARRAY=(`echo ${hostAddress}`)
U_ARRAY=(`echo ${userName}`)
P_ARRAY=(`echo ${password}`)
I_ARRAY=(`echo ${instanceCount}`)
# Ok, time to announce success, let's printout each of the arrays
echo ${H_ARRAY[@]}
echo ${U_ARRAY[@]}
echo ${P_ARRAY[@]}
echo ${I_ARRAY[@]}
在执行该脚本,我得到这个错误: eval [1]:-ne:未找到[没有这样的文件或目录]
任何人都可以请帮我解决这个问题吗?
答
一些一般性的问题:
- Use
$(command)
rather than`command`
. - 而不是使用
eval
(which is evil),只需创建一个函数来提取任意元素(实际上就是你的grep
线)和运行的4倍。 - 要add items to an array(而不是替换内容,像你这样做),你可以使用
array_variable+=(array_element)
- Use More Quotes™
+0
感谢它的工作 – 2014-11-26 06:08:40
答
如果你真的确定你需要的echo -e
的影响,正在运行ksh93的或mksh,你可以使用nameref进行间接转让,避免了eval
的需要:
typeset -n ref="$tag"
ref=$(echo -ne "$OUT")
如果你使用bash,我建议如下(其中还执行echo -e
的反斜杠序列扩展):
printf -v "$tag" %b "$OUT"
'echo'是一个内置的shell以及一个二进制文件。试试'/ bin/echo' – Sobrique 2014-11-03 11:23:56
我试过了,但是同样的错误... – 2014-11-03 11:47:14
为什么这段代码需要使用'eval'呢? – 2014-11-03 13:01:58