shell用eval處理複雜變量

這裏說的處理複雜變量就是定義並使用包含變量的變量,這在高級語言中幾乎不須要什麼特殊處理,但shell中就須要用到eval,下邊是腳本中的部分代碼,供參考:shell

#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,7spa

引用時,也要經過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中讀取到的值,替換模板中的佔位符。code

eval命令將會首先掃描命令行進行全部的置換,而後再執行該命令。該命令適用於那些一次掃描沒法實現其功能的變量。簡單理解就是將命令執行兩次,獲得第二次執行的結果。blog

"$"theTenant1_$T1count中第二個"$"但願被先執行,因此沒用雙引號,第一個"$"但願被後執行,因此加了個雙引號。模板

相關文章
相關標籤/搜索