shell用eval处理复杂变量

这里说的处理复杂变量就是定义并使用包含变量的变量,这在高级语言中几乎不需要什么特殊处理,但shell中就需要用到eval,下边是脚本中的部分代码,供参考:

#confFile 包含下边一行
#SLOTS_FOR_TENANT1=1,3,5,7
#部分代码:
theTenant1_blades=`cat $confFile | grep SLOTS_FOR_TENANT1 | awk -F ',' '{print NF}'`
count=1
while (($count <= $theTenant1_blades))
do
eval theTenant1_$count=`cat $confFile | grep SLOTS_FOR_TENANT1 | cut -d "=" -f 2 | cut -d "," -f $count`
let "count++"
done

这段程序执行结束后,变量theTenant1_blades等于4,theTenant1_1到theTenant1_4会分别被赋值1,3,5,7

引用时,也要通过eval:

T1count=1
while (($T1count <= $theTenant1_blades))
do
  eval slotid="$"theTenant1_$T1count
  sed -i "s/<X-Y${T1count}>/0-${slotid}/g" $1
  let "T1count++"
done

这段代码通过从配置文件confFile中读取到的值,替换模板中的占位符。

eval命令将会首先扫描命令行进行所有的置换,然后再执行该命令。该命令适用于那些一次扫描无法实现其功能的变量。简单理解就是将命令执行两次,得到第二次执行的结果。

"$"theTenant1_$T1count中第二个"$"希望被先执行,所以没用双引号,第一个"$"希望被后执行,所以加了个双引号。

posted @ 2016-09-23 16:29  自学未成才  阅读(1931)  评论(0编辑  收藏  举报