用Shell編寫程序時,常常不得不面對交互問題,而Shell本身往往難以自動完成交互。若交互內容很多,直接編寫Expect腳本自然更合適;但若交互內容很少,兼顧Shell的易用性,在Shell腳本中嵌入一段Expect的Here Document會更加方便靈活。
如下例所示,Expect Here Document可以直接運行,並將運行結果賦給KSH變量rcs_stat:
#!/bin/ksh
autoload formatAPnum
# Set the lab name, COOLLAB
. $COOLXDIR/.netlabs
# Get the RCS cell list
set -A RCSs
typeset -i nx=0
cat $COOLXDIR/.coolcell2dcs | while read cell
do
if [[ "$cell" = c* ]]
then
rcs=${cell%%$COOLLAB*}
RCSs[$nx]=${rcs#c}
nx=$nx+1
fi
done
# Check RCS status
typeset -i loopCount=0
rcs_cnt=${#RCSs[*]}
B_server=$(formatAPnum $BserverAP)
while [ "${#RCSs[*]}" != 0 -a $loopCount -lt 720 ] # wait at most 2 hours
do
loopCount=${loopCount}+1
nx=0
while [ $nx -lt $rcs_cnt ]
do
rcs_stat="OOS"
rcs_stat=$(
expect - <<!
log_user 0
set timeout 20
spawn $COOL_RSH ap$B_server TICLI
send "op:cell ${RCSs[$nx]}\r"
expect {
timeout {puts "OOS\n"}
"*DL(S) DOWN" {puts "OOS\n"}
"*DL(S) UP" {puts "UP\n"}
}
!
)
if [ "$rcs_stat" = "UP" ]
then
coolprint - "RCS cell ${RCSs[$nx]} is up."
unset RCSs[$nx]
fi
nx=${nx}+1
done
[ -n "${RCSs[*]}" ] && sleep 10
done
coolprint - "All RCSs are up."
exit 0
這個例子展示了如何在Shell的循環中嵌入Expect Here Document,去自動完成登錄、發送命令、判斷返回等交互,並將結果回填到Shell變量中繼續後續邏輯,兼顧了自動化與腳本的靈活性。