在使用Shell寫程式時,有時不得不面對互動的問題——可惜shell往往無法自動完成互動。如果互動的內容很多,自然是直接應用Expect指令碼比較方便;如果互動的內容很少,而且考慮到Shell的易用性,在Shell指令碼中建立一個Expect 的Here Document更加方便靈活。
如下例所示,Expect Here Document可以直接運行並將運行結果賦給KSH變數rcs_stat。
#!/bin/kshautoload formatAPnum# Set the lab name, COOLLAB. $COOLXDIR/.netlabs# Get the RCS cell listset -A RCSstypeset -i nx=0cat $COOLXDIR/.coolcell2dcs | while read celldoif [[ "$cell" = c* ]]thenrcs=${cell%%$COOLLAB*}RCSs[$nx]=${rcs#c}nx=$nx+1fidone# Check RCS statustypeset -i loopCount=0rcs_cnt=${#RCSs[*]}B_server=$(formatAPnum $BserverAP)while [ "${#RCSs[*]}" != 0 -a $loopCount -lt 720 ] # wait at most 2 hoursdoloopCount=${loopCount}+1nx=0while [ $nx -lt $rcs_cnt ]dorcs_stat="OOS"rcs_stat=$(expect - <<!log_user 0set timeout 20spawn $COOL_RSH ap$B_server TICLIsend "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" ]thencoolprint - "RCS cell ${RCSs[$nx]} is up."unset RCSs[$nx]finx=${nx}+1done[ -n "${RCSs[*]}" ] && sleep 10 donecoolprint - "All RCSs are up."exit 0