歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> Shell中使用Expect Here Document

Shell中使用Expect Here Document

日期:2017/3/1 10:23:41   编辑:SHELL編程

在使用Shell寫程序時,有時不得不面對交互的問題——可惜shell往往無法自動完成交互。如果交互的內容很多,自然是直接應用Expect腳本比較方便;如果交互的內容很少,而且考慮到Shell的易用性,在Shell腳本中創建一個Expect 的Here Document更加方便靈活。

如下例所示,Expect Here Document可以直接運行並將運行結果賦給KSH變量rcs_stat。

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