Shell中使用Expect Here Document


在使用Shell写程序时,有时不得不面对交互的问题——可惜shell往往无法自动完成交互。如果交互的内容很多,自然是直接应用Expect脚本比较方便;如果交互的内容很少,而且考虑到Shell的易用性,在Shell脚本中创建一个Expect 的Here Document更加方便灵活。

如下例所示,Expect Here Document可以直接运行并将运行结果赋给KSH变量rcs_stat。

  1. #!/bin/ksh   
  2.   
  3. autoload formatAPnum  
  4.   
  5. # Set the lab name, COOLLAB   
  6. . $COOLXDIR/.netlabs  
  7. # Get the RCS cell list   
  8. set -A RCSs  
  9. typeset -i nx=0  
  10. cat $COOLXDIR/.coolcell2dcs | while read cell  
  11. do  
  12.     if [[ "$cell" = c* ]]  
  13.     then  
  14.         rcs=${cell%%$COOLLAB*}  
  15.         RCSs[$nx]=${rcs#c}   
  16.         nx=$nx+1  
  17.     fi  
  18. done  
  19.   
  20. # Check RCS status   
  21. typeset -i loopCount=0  
  22. rcs_cnt=${#RCSs[*]}   
  23. B_server=$(formatAPnum $BserverAP)  
  24. while [ "${#RCSs[*]}" != 0 -a $loopCount -lt 720 ]  # wait at most 2 hours  
  25. do  
  26.     loopCount=${loopCount}+1  
  27.   
  28.     nx=0  
  29.     while [ $nx -lt $rcs_cnt ]  
  30.     do  
  31.         rcs_stat="OOS"  
  32.         rcs_stat=$(  
  33. expect - <<!  
  34. log_user 0  
  35. set timeout 20  
  36. spawn $COOL_RSH ap$B_server TICLI  
  37. send "op:cell ${RCSs[$nx]}\r"  
  38. expect {  
  39.     timeout {puts "OOS\n"}  
  40.     "*DL(S) DOWN" {puts "OOS\n"}  
  41.     "*DL(S) UP" {puts "UP\n"}  
  42. }  
  43. !  
  44.         )  
  45.   
  46.         if [ "$rcs_stat" = "UP" ]  
  47.         then  
  48.             coolprint - "RCS cell ${RCSs[$nx]} is up."  
  49.             unset RCSs[$nx]  
  50.         fi  
  51.   
  52.         nx=${nx}+1  
  53.     done  
  54.   
  55.     [ -n "${RCSs[*]}" ] && sleep 10   
  56. done  
  57.   
  58. coolprint - "All RCSs are up."  
  59. exit 0  

相关内容