這里說的處理復雜變量就是定義並使用包含變量的變量,這在高級語言中幾乎不需要什么特殊處理,但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中第二個"$"希望被先執行,所以沒用雙引號,第一個"$"希望被后執行,所以加了個雙引號。